YetAnotherDeveloper
YetAnotherDeveloper

Reputation: 846

How to Group and Order in a LINQ Query

I would like to group & order by in a query builder expression. The following query gets me close to what i want but the order by does not appear to be working.

what i have is an object that has unique ids but some will have a common versionId. I would like to get the last edited item of the same versionId. So only one item per version id and i want it to be the last edited one.

IQueryable<Item> result = DataContext.Items.Where(x => (x.ItemName.Contains(searchKeyword) ||
                                  x.ItemDescription.Contains(searchKeyword))
                                  .GroupBy(y => y.VersionId)
                                  .Select(z => z.OrderByDescending(item => item.LastModifiedDateTime).FirstOrDefault());

Edit: I don't really care about the order of the result set, i really just care about what item within the grouping is returned. I want to make sure that the last edited Item within a versionId group is return.

Upvotes: 2

Views: 682

Answers (1)

SLaks
SLaks

Reputation: 887275

Your z parameter contains the individual group objects.

By calling OrderBy inside of Select, you're ordering the items in each group, but not the groups themselves.

You need to also call OrderBy after Select, like this:

.Select(z.OrderByDescending(item => item.LastModifiedDateTime).FirstOrDefault())
.Where(item => item != null)
.OrderByDescending(item => item.LastModifiedTime)

Upvotes: 2

Related Questions