How to group and order in a LINQ query
I would like to group and order in a builder expression of a query. The following query gets me closer to what I want, but the order doesn't work.
I have an object with unique IDs, but some will have a common version file. I would like to get the last edited item of the same versionId. So there is only one item for the version id, and I want it to be the last one edited.
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 care about the order of the result set, I just care about which item in the group gets returned. I want the last edited item in the versionId group to be returned.
a source to share
The parameter z
contains individual group objects.
By calling OrderBy
internally Select
, you order the items in each group, but not the groups themselves.
You also need to call OrderBy
after Select
, for example:
.Select(z.OrderByDescending(item => item.LastModifiedDateTime).FirstOrDefault())
.Where(item => item != null)
.OrderByDescending(item => item.LastModifiedTime)
a source to share