Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL GroupBy Max() lambda

Tags:

c#

lambda

linq

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.

like image 725
Since_2008 Avatar asked Feb 15 '12 22:02

Since_2008


People also ask

Is LINQ faster than lambda?

In some cases LINQ is just as fast if not faster than other methods, but in other cases it can be slower. We work on a project that we converted to linq and the data lookup is faster but the merging of data between two tables is much slower.

How does GroupBy work LINQ?

The working of the GroupBy operator is similar to the SQL GroupBy clause. It is used to return the group of elements which share the common attributes or key from the given sequence or collection. Every group is represented by IGrouping<TKey, TElement> object.

What is lambda expression in LINQ?

A lambda expression is a convenient way of defining an anonymous (unnamed) function that can be passed around as a variable or as a parameter to a method call. Many LINQ methods take a function (called a delegate) as a parameter.

What does LINQ GroupBy return?

GroupBy & ToLookup return a collection that has a key and an inner collection based on a key field value. The execution of GroupBy is deferred whereas that of ToLookup is immediate. A LINQ query syntax can be end with the GroupBy or Select clause.


1 Answers

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),
         });
like image 199
DaveShaw Avatar answered Oct 13 '22 11:10

DaveShaw