6

Please help me convert this to a lambda expression

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

Thanks!

EDIT: Here's what I have so far.

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

When I add the GroupBy, my Select says there's no definition for x.UserID and x.Created.

2
  • When I add the group by, my select breaks. Does the group by eliminate all the other fields or something?
    – Since_2008
    Feb 15, 2012 at 22:56
  • 1
    Remember, after group by you have IEnumerable<IGrouping<TGroupingKey, TYourOriginalClass>> instead of your original IEnumerable<TYourOriginalClass>. Guys below show you practical examples of the fact.
    – Krizz
    Feb 15, 2012 at 23:01

3 Answers 3

15

Here you go:

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

Regarding your edit, as I said in comment, in .Select(x => new { x.UserID, x.Created }), x is no longer a UserHistory, it is IGrouping<int, UserHistory>(1), which does not have UserID and Created properties, but only Key property, which is an user id and implements IEnumerable to enumerate all items for the given key (user id).

Use @DaveShaw snippet as it is the most correct one and most efficient.

(1) I assume UserID is int.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.