bevacqua
bevacqua

Reputation: 48566

LINQ Query question

I have a list with the following info

date, name, and a few statistics

The names can repeat, but they don't necessarily.

so for instance I could have

5, today, "John"
4, today, "Kim"
3, today, "Peter"
2, yesterday, "Kim"
1, yesterday, "Tim"

I want a query that retrieves the latest records for each user. In my example that would be records 5, 4 and 1.

Do I necessarily have to match each record against the whole database in order to find out?
What would be the best performing query to achieve this?

Upvotes: 0

Views: 87

Answers (2)

as-cii
as-cii

Reputation: 13039

Maybe something like this could work?

var linq = people.GroupBy(a => a.Name).Select(a => a.OrderBy(a => a.Date).Last());

Longer version:

var linq = from person in people
           group person by person.Name into grouped
           select grouped.OrderBy(a => a.Date).Last();

Upvotes: 3

Roland Mai
Roland Mai

Reputation: 31097

Here's what I think:

from u in context.Users
group u by u.UserID into grouped
select grouped.OrderByDescending(g => g.Date).First()

Upvotes: 0

Related Questions