I was trying simple thing, form a collection of employees I want to fetch top two maximum employees list. But remember there can be multiple employee with the same salary so I want all of them if they fall in max two salary range. below is my collection that I am using:
List<Employee> Employees = new List<Employee>
{
new Employee {EmployeeID = 1,EmployeeName ="A", Department ="Dept1", Salary = 10000 },
new Employee {EmployeeID = 5,EmployeeName ="A1", Department ="Dept2", Salary = 12000 },
new Employee {EmployeeID = 2,EmployeeName ="B", Department ="Dept1", Salary = 20000 },
new Employee {EmployeeID = 3,EmployeeName ="C", Department ="Dept1", Salary = 20000 },
new Employee {EmployeeID = 6,EmployeeName ="B1", Department ="Dept2", Salary = 4500 },
new Employee {EmployeeID = 4,EmployeeName="D", Department ="Dept1", Salary = 30000 },
};
and Employee class is:
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string Department { get; set; }
public long Salary { get; set; }
}
and below is my query:
var result1 = from x in Employees
group x by x.Salary into g
from y in g.OrderBy(x=>x.Salary).Take(2)
select new { y.EmployeeID };
foreach (var item in result1)
{
Console.WriteLine(item.EmployeeID);
}
What I'm trying to do here is, first I am grouping all the employees based on their salaries. Then order these groups and take first two groups using TAKE extension method and then print all the employee those are in these two groups.
But I don't know why it's printing all the employees; it's not even ordering them. Can someone please share some thoughts and tell me what's wrong with this query?
What I have tried:
I've tried change the position of order by and group by still getting the same results.