1

下面我有表 - 公司

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

我想按名称对记录进行分组,并且从每个组中只返回一条具有最大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();
4

2 回答 2

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
                    };
于 2012-06-21T21:55:14.243 回答
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;  
于 2012-06-21T22:13:31.847 回答