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.
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.
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.
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.
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.
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),
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With