1

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?

ekad
  • 14,436
  • 26
  • 44
  • 46
Sarge
  • 388
  • 1
  • 4
  • 22

1 Answers1

3

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.

Enes
  • 1,115
  • 7
  • 12
  • Thanks a lot, worked perfectly. I used it as; `List dbResult = entities.Forms.GroupBy(e => e.Title).SelectMany(e => e.OrderByDescending(e => e.CreationDate).Take(3)).ToList();` Can you tell me about the orderBy usage in selectMany? – Sarge Dec 11 '14 at 11:03
  • 1
    Combination of SelectMany and OrderBy is there to do inner select to get item with max CreationDate. So not sure if you should do "take(3)" there. I would do another .Take(3) after SelectMany to get only 3 forms. – Enes Dec 11 '14 at 11:06
  • It worked as I wanted it to be, thanks again for the explanation. – Sarge Dec 11 '14 at 11:15
  • 1
    I red you question again. And yes, you were correct. That would return you 3 latest Forms of same title. – Enes Dec 11 '14 at 11:37