将行分组并从每个组中获取最大值。

时间:2012-06-21 21:51:09

标签: c# linq entity-framework-4

下面我有表 - 公司

  id name value year
    1  IBM   10   2011
    2  IBM   30   2012
    3  IBM   10   2012
    4  C     10   2010

我想按 name 对记录进行分组,并且每个组只返回一条最大 id 的记录。所有结果都合并到使用linq的公司列表中,其中2011年更大。对于我的示例,输出应为 - “3 IBM 10 2012”

我确实写过一些东西但没有用。

var a = from x in companies where x.year > 2011
                  group x by new {x.name, x.value, x.ID, x.year } into g
                  select new {
                                  g.Key.name,
                                  g.Key.value,
                                  g.Max(a=>a.ID),
                                  g.Key.value
                              };
 return a.ToList();

2 个答案:

答案 0 :(得分:0)

请勿在分组中包含该ID。实际上,如果您只是希望它们按公司名称分组,请不要包含任何其他属性:

// set up for testing
var companies =
    from c in new[]{"1,IBM,10,2011", "2,IBM,30,2012", "3,IBM,10,2012", "4,C,10,2010"}
    let cp = c.Split(',')
    select new {id=int.Parse(cp[0]), name=cp[1], value=int.Parse(cp[2]), year=int.Parse(cp[3])};

// query
var q = from x in companies where x.year > 2011
        group x by x.name into g
        let top = g.OrderByDescending(x => x.id).FirstOrDefault()
        select new {
                        top.name,
                        top.value,
                        top.id,
                        top.year
                    };

答案 1 :(得分:0)

试试这个:

  var a = from x in companies
                where x.Year > 2011
                group x by new { x.Name } into g
                from x1 in companies
                where x1.ID == (from x2 in g select x2.ID).Max()
                select x1;   

或更高效的东西:

var a = from x in companies
                    where x.Year > 2011
                    group x by new { x.Name } into g
                    join x2 in companies on (from x3 in g select x3.ID).Max() equals x2.ID
                    select x2;