frenchie
frenchie

Reputation: 51927

Query for first two elements of a group by descending

I have a table that looks like this:

FruitID | FruitDate | FruitType
  23    |  10/20/14 |   3
  32    |  10/12/14 |   3
  39    |  09/23/14 |   3

There are many FruitTypes and I want to extract a list of object models that contains the last two Fruits, for instance {FruitID : 23, Date: 10/20}, {FruitID : 32, Date: 10/12}

This is what I have:

var Output = (from f in MyDC.Fruits
              where ... some condition
              orderby f.FruitDate descending
              group f by f.FruitType in FruitGroups
              select.... new FruitModel()
              {
                   FruitID = ...
                   FruitDate = ...
                   FruitType = ...

              }).ToList();

I'm having trouble take the latest 2. How can I get back a list of the last 2 of each FruitType?

Upvotes: 0

Views: 129

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 21795

Try this:-

var query = from fruit in fruitsData
                        group fruit by fruit.FruitType into g
                        select new
                        {
                            FruitType = g.Key,
                            Fruits = g.OrderByDescending(x => x.FruitDate).Take(2)
                        };

Working Fiddle.

Upvotes: 0

Louis Michael
Louis Michael

Reputation: 398

var Output = (from f in MyDC.Fruits
              where ... some condition
              orderby f.FruitDate descending
              group f by f.FruitType in FruitGroups
              select.... new FruitModel()
              {
                   FruitID = ...
                   FruitDate = ...
                   FruitType = ...

              }).Take(2).ToList();

Follow-up edit

Added a missing from clause; this is the query:

var Output = (from f in MyDC.Fruits
              where ... some condition
              orderby f.FruitDate descending
              group f by f.FruitType in FruitGroups
              from t in FruitGroups
              select new FruitModel()
              {
                   FruitID = t.FruitID,
                   FruitDate = t.FruitDate
                   FruitType = t.FruitType

              }).Take(2).ToList();

Upvotes: 1

Related Questions