// 第一种
var ids1 = logs.GroupBy(e => new { ChangeID = e.ChangeID, ChangeType = e.ChangeType })
.Select(e => e.Max(data => data.ID));
var filterLogs1 = logs.Where(e => ids1.Contains(e.ID));
// 第二种
var ids2 = from log1 in logs
group log1 by new { ChangeID = log1.ChangeID, ChangeType = log1.ChangeType } into g
select g.Max(p => p.ID);
var filterLog2 = from log in logs
where (ids2.Contains(log.ID))
select log;
from c in changelogs group p by c.ID into g select g
基本的语法是这样的 因为没开VS 所以只能写个大概 下面有具体的语法
http://www.cnblogs.com/qiuweiguo/archive/2011/06/08/2074949.html
能不能帮忙写一下,这些文章我都看过了,但是怎么也写不出想要的结果
呵呵.原来大家都被耍了,你面试的时候也这么说?
数据库查询根本在于sql,实体框架在围绕sql转,何必这么绕
select * from changelogs where id in( select max(ID) from changelogs group by changeID,changetype)
这条语句注定比你的linq高了很多.原本linq就一个鸡肋
SELECT MAX([t0].[ID]) AS [ID]
FROM [dbo].[ChangeLogs] AS [t0]
GROUP BY [t0].[ChangeID], [t0].[ChangeType]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 4.0.30319.33440
这是linq生成的sql语句,鸡肋吗?
SELECT [t0].[ID], [t0].[ChangeID], [t0].[ChangeType], [t0].[ChangeMethod], [t0].[CreateDate]
FROM [dbo].[ChangeLogs] AS [t0]
WHERE EXISTS(
SELECT NULL AS [EMPTY]
FROM (
SELECT MAX([t1].[ID]) AS [value]
FROM [dbo].[ChangeLogs] AS [t1]
GROUP BY [t1].[ChangeMethod], [t1].[ChangeType]
) AS [t2]
WHERE [t2].[value] = [t0].[ID]
)
这是整句的
@枫叶染深秋: 用ADO.NET和它比较一下就知道了,用了多久生成。
其次,在复杂一点你试试
已经解决changelogs.GroupBy(l => new { l.changeID, l.changetype }).Select(k => new { ID = k.Max(m => m.id) })
你可以下载LinqPad自己试试生成的标准语句是怎么样的