简体   繁体   English

如何使用LINQ查找具有最小值的前N个项目

[英]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". 我想拿到第6项的offerList有民RegularPrice价值,其OfferCode包含“数字电视”。 I tried the following LINQ but it retrieves only one item instead of 6. What am I doing wrong? 我尝试了以下LINQ,但它仅检索一项而不是6。我在做什么错?

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();

Order by RegularPrice and take the first 6 rows. RegularPrice并获取前6行。

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. 这将为您提供价格最低的前六个记录。

The only plausible explanation to this is that there are not 6 items which remain after your filter. 对此的唯一合理的解释是,过滤器后没有剩余6个项目。

The Take will take 6 if there are 6 or more items after filter. 如果过滤器后有6个或更多项目,则Take将花费6。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM