Stack Overflow
Stack Overflow

Reputation: 11

How to find first N items with Min values using LINQ

I am trying to get the first 6 items of offerList that have Min RegularPrice value and whose OfferCode contains "dtv". I tried the following LINQ but it retrieves only one item instead of 6. What am I doing wrong?

List<Offer> dtvOffers = offerList.Where(x => 
    (x.ListPrice.CommodityPrice.RegularPrice == offerList.Min(y => 
        y.ListPrice.CommodityPrice.RegularPrice)) && 
    (x.OfferCode.ToLower().Contains("dtv")))
    .Take(6).ToList();

Upvotes: 0

Views: 603

Answers (2)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

The only plausible explanation to this is that there are not 6 items which remain after your filter.

The Take will take 6 if there are 6 or more items after filter. If not it take what's left. Can also return a blank collection if none left.

Oh and BTW, calculate this line before hand. No use, evaluating for each and every iteration.

var min = offerList.Min(y => y.ListPrice.CommodityPrice.RegularPrice);

List<Offer> dtvOffers = offerList.Where(x => 
       (x.ListPrice.CommodityPrice.RegularPrice == min) &&
       (x.OfferCode.ToLower().Contains("dtv")))
    .Take(6).ToList();

Upvotes: 1

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

Order by RegularPrice and take the first 6 rows.

offerList.Where(x => x.OfferCode.ToLower().Contains("dtv"))
         .OrderBy(x.ListPrice.CommodityPrice.RegularPrice)
         .Take(6)
         .ToList();

This will give you the first six records with the lowest price.

Upvotes: 3

Related Questions