LINQ group by和max子句用法

时间:2013-05-05 05:40:38

标签: linq

我在Employee类下面有3个重要字段

public class Employee
{
    public string Name
    {
        get;
        set;
    }

    public string Department
    {
        get;
        set;
    }

    public double Salary
    {
        get;
        set;
    }
}

我有这样的员工名单。我想找出每个部门的名字员工 他/她的部门工资最高。

我写了下面的查询,但它不起作用。

List<Employee> list = new List<Employee>();
        list.Add(new Employee { Name="Hemant",Salary=10,Department="PTS"});
        list.Add(new Employee { Name = "Gunjan", Salary = 11, Department = "PTS" });
        list.Add(new Employee { Name = "Akshay", Salary = 8, Department = "PTS" });
        list.Add(new Employee { Name = "Omkar", Salary = 10, Department = "EBG" });
        list.Add(new Employee { Name = "Hemant1", Salary = 14, Department = "EBG" });

        var query1 = from e in list
                    group e by e.Department into g
                    select new { Dept = g.Key,MaxSal = g.Max((e) => e.Salary )};

        foreach (var item in query1)
        {
            Console.WriteLine("Department : " + item.Dept + "  :  " + " Salary is : " + item.MaxSal);                
        }

但是上面的代码不起作用,我无法选择员工姓名。我想我必须使用升序/降序子句并选择第一个或最后一个记录。但我无法弄明白。有人可以帮忙。

此致 Hemant Shelar

1 个答案:

答案 0 :(得分:3)

是的,您应该OrderByDescending然后获取First

var query1 = list.GroupBy(x => x.Department)
                 .Select(g => g.OrderByDescending(x => x.Salary).First());

以下是控制台代码:

foreach (var item in query1)
{
    string output = string.Format("Deparment: {0}, Name: {1}, Max Salaray: {2}",
                                  item.Department, item.Name, item.Salary
        );

    Console.WriteLine(output);
}