LINQ to SQL GroupBy Max()lambda

时间:2012-02-15 22:52:30

标签: c# linq lambda

请帮我转换为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的定义。

3 个答案:

答案 0 :(得分:13)

你走了:

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),
         });

答案 1 :(得分:0)

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)
             };

答案 2 :(得分:0)

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

使用@DaveShaw片段,因为它是最正确且效率最高的片段。

(1)我认为UserIDint