How to select from a list with Linq based on id and datetime value
How to select from a list with Linq, based on id and datetime value. I want the latest item from each id.
So I have a list that has an ID and a date time for each object.
I know how to get just the items that are from a certain id.
var foundListings = (from listing in db.Listings
where listing.UserID == idToFind
select listing);
But what I want to do is get the latest item from eac开发者_开发技巧h ID. So if I have a List with let's say 5 Listings and their are only 2 ids in there. I want to query and get just 2 items with the latest date.
Is this possible with Linq? I am certain I can do it iteratively going through the list with a for loop but wanted to see if I could do it with Linq and this is a little beyond my linq skills.
You'll probably want to use group by
to create groups based on the ID and then select minimum from each group. I didn't test it, but the structure should look like this:
var q = from listing in db.Listings
group by listing.UserID into g
select g.OrderBy(el => el.Value).First();
Using the OrderBy
clause is a bit unfortunate, because it implies that you want to search all items. Unfortunatelly, there is no operator to return the item that is largest by some property. Alternatively, you could first find maximum and then find some element which has that value:
var q = from listing in db.Listings
group by listing.UserID into g
let max = g.Max(el => el.Value)
select g.Where(el => el.Value == max).First();
This may be slightly more efficient (especially for in-memory runs) because it doesn't need to sort the entire group.
var result = from listing in db.Listings
group listing by listing.ID into g
select g.OrderByDescending(l => l.DateTime).First();
精彩评论