LINQ to SQL GroupBy Max() lambda

本文关键字:lambda Max GroupBy to SQL LINQ | 更新日期: 2023-09-27 18:24:51

请帮助我将其转换为lambda表达式

SELECT [UserID], MAX(Created) Created
FROM [UserHistory]
WHERE userid IN (14287)
GROUP BY [UserID]

谢谢!

编辑:这是我迄今为止所拥有的。

List<T> list;  //list is populated
table.Where(x => list.Select(y => y.ClientId).Contains( x.UserID))
                    .GroupBy(x => x.UserID)
                    .Select(x => new { x.UserID, x.Created })
                    .ToList();

当我添加GroupBy时,我的Select表示没有x.UserID和x.Created.的定义

LINQ to SQL GroupBy Max() lambda

开始:

var userIDs = new[] {14287, };
var results =
dataContext.UserHistories
.Where(user => userIDs.Contains(user.userID))
.GroupBy(user => user.userID)
.Select(
     userGroup =>
         new 
         {
             UserID = userGroup.Key,
             Created = userGroup.Max(user => user.Created),
         });

关于您的编辑,正如我在评论中所说,在.Select(x => new { x.UserID, x.Created })中,x不再是UserHistory,而是IGrouping<int, UserHistory>(1),它没有UserIDCreated属性,而只有Key属性,它是一个用户id,并实现IEnumerable来枚举给定密钥(用户id)的所有项。

使用@DaveShaw片段,因为它是最正确、最有效的。

(1) 我假设UserIDint

var query = from history in context.UserHistories
                where ( new[] {14287} ).Contains(history.userID)
                group history by history.UserID into g
             select new 
             {
                 UserId = g.Key,
                 MaxCreated = g.Max( x => x.Created)
             };