views:

58

answers:

1

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.

+2  A: 

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)
SLaks
I'm not so worried about the order of the different versionIds(the outer orderby), i'm more concerned within a given versionId. My First query does not seem to apply the order to the items within that grouping based on versionId.
YetAnotherDeveloper
Your code should already do that.
SLaks
thats what i was thinking...
YetAnotherDeveloper