2012-06-21 44 views
0

下面我有表 - 由并从每个组只返回一个记录最大ID公司将行分组并从每个组中获取最大值。

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

我想组记录。所有结果合并到2011年使用linq的公司列表中。对于我的示例输出结果应该是 - “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(); 
+1

你的意思是你希望它返回“3 IBM 10 2012”,是吗? – WEFX

+0

你想按x.ID分组吗? –

+0

是的,我的意思是返回“3 IBM 10 2012” – user570715

回答

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; 
+0

使用这个当我尝试返回a.ToList();在函数结束时抛出错误Error 不能隐式地将类型'System.Collections.Generic.List '转换为'System.Collections.Generic.List ' – user570715

+0

好的。我会更新答案。 –

+0

@ user570715完成。 –

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 
        }; 
+0

如果我不通过ID分组,我不能做g.Max(a => a.ID),但ID将无法访问。 – user570715

+0

对不起,我试过这种方式,但它会抛出错误 - 错误无效的匿名类型成员声明。匿名类型成员必须声明为成员分配,简单名称或成员访问权限。 – user570715

+0

@ user570715:您的原始代码存在各种其他问题。我刚刚发布了一个绝对有效的更新。 (我在LINQPad中测试过) – StriplingWarrior