Take Last n Items from a Grouped and Ordered List using Entity Framework

129 Views Asked by At

I have a list of Forms, and in this list the forms with the same Title denotes the different version of the that form, the one with closest Creation Time (which is DateTime type) is newer version.

So I want to select each forms last n versions using entity framework code. I used this but it still brings me the first (oldest) n versions.

List<Forms> dbResult = entities.Forms.OrderByDescending(e => e.CreationDate)
                                     .GroupBy(e => e.Title)
                                     .SelectMany(e => e.Take(n))
                                     .ToList();

Where do I go wrong?

1

There are 1 best solutions below

4
On BEST ANSWER

Try this:

var result = entities.Forms
            .GroupBy( x => x.Title )
            .SelectMany( g => g.OrderByDescending(v => v.CreationDate).Take(1) );

This would return you forms of same title with maximum CreationDate. You can do additional filtering to take n items and order them in any way.