小编xwr*_*ith的帖子

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

我已经开始在.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
Run Code Online (Sandbox Code Playgroud)

我已经在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 …
Run Code Online (Sandbox Code Playgroud)

c# linq-to-entities .net-3.5

0
推荐指数
1
解决办法
5393
查看次数

标签 统计

.net-3.5 ×1

c# ×1

linq-to-entities ×1