LINQ到实体:容易找到SQL最大值,但很难在LINQ? [英] Linq-to-entities: Easy to find max value in SQL, but difficult in LINQ?
问题描述
我已经开始使用LINQ到实体.NET 3.5,和我遇到一个情况下,我可以做在SQL中真正的轻松,但我有很大的困难LINQ。 我有一个表中有三个字段一个SQL数据库,出于这个例子中,我会打电话给他们富,酒吧,和foo_index和填充他们像这样:
I've started using Linq-to-entities with .NET 3.5, and I've come across a scenario that I can do real easy in SQL, but I'm having great difficulty with linq. I have a table in a SQL database with three fields, for purposes of this example I'll call them foo, bar, and foo_index and populate them like so:
块引用
FOO |酒吧| foo_index
foo | bar | foo_index
555 101 1
555 101 1
555 101 2
555 101 2
555 101 3
555 101 3
555 101 4
555 101 4
555 101 5
555 101 5
要得到的是什么吧最大foo_index其中foo = 555 SQL是
To get what bar is at the max foo_index where foo=555 the SQL is
SELECT bar, max(foo_index) as max_foo_index
FROM T
WHERE foo=555
GROUP BY bar
我已经写了一些LINQ到实体code在C#中的作品,但我有一种感觉,有一种更高贵的解决方案在那里,而且我错过了一些概念,将进行以下容易得多。此外,有没有什么办法其他然后一个foreach获取数据了变种的?
I've written some linq-to-entities code in C# that works, but I have a feeling there is a much more elegent solution out there, and that I'm missing some concept that would make the following much easier. Also, is there any way other then a foreach to get the data out of a 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;
}
任何帮助或指导,将AP preciated,谢谢!
Any help or guidance would be appreciated, Thanks!
推荐答案
我觉得这应该工作:
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
So basically you're taking the same approach as in the SQL: group the data, then take the key for the group and the maximum FOO_INDEX within the group.
这篇关于LINQ到实体:容易找到SQL最大值,但很难在LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!