Linq-to-entities:在SQL中很容易找到最大值,但在LINQ中很难?

时间:2010-07-21 13:10:13

标签: c# .net-3.5 linq-to-entities

我已经开始在.NET 3.5中使用Linq-to-entities,而且我遇到了一个我可以在SQL中轻松实现的方案,但我对linq有很大的困难。 我在SQL数据库中有一个包含三个字段的表,为了这个例子,我将它们称为foo,bar和foo_index,并像这样填充它们:

  

块引用

     

foo |吧| foo_index

     

555 101 1

     

555 101 2

     

555 101 3

     

555 101 4

     

555 101 5

要获得最大foo_index处的条形,其中foo = 555,SQL为


SELECT bar, max(foo_index) as max_foo_index
FROM T
WHERE foo=555
GROUP BY bar

我已经在C#中编写了一些linq-to-entities代码,但是我觉得有一个更加优雅的解决方案,而且我错过了一些可以使以下内容更容易的概念。另外,有没有其他方法可以从var中获取数据?


db_entity db = new db_entity();

var q =
     from table in db.T
     where table.FOO == 555
     select new { table.BAR, table.FOO_INDEX };

var q2 = 
     from t2 in q
     where t2.FOO_INDEX == table.Max(r => r.FOO_INDEX)
     select new { t2.BAR };

int result = 0;

foreach (var record in q2}
{
    result = record.BAR.Value;
}

任何帮助或指导将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:8)

我认为这应该有效:

var query = from item in db.T
            where item.FOO == 555
            group item by item.BAR into g
            select new { Bar = g.Key, Max = g.Max(x => x.FOO_INDEX) };

所以基本上你采用与SQL中相同的方法:对数据进行分组,然后获取组的密钥和组内的最大FOO_INDEX。

答案 1 :(得分:2)

您可以像在SQL中一样将LINQ to Entities中的元素分组。语法类似于:

var q = from t in db.T
        where t.FOO == 555
        group t by t.BAR into g
        select new { 
                       Bar = group.Key, 
                       Max = g.Max(b => b.FOO_INDEX) 
                   };