如何使用LINQ

时间:2017-04-19 07:49:51

标签: c# linq

我正在尝试获取offerList前{6}项,其RegularPrice值为OfferCode,其中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(); 包含“dtv”。我尝试了以下LINQ,但它只检索了一个项而不是6.我做错了什么?

    //For .map(res => res.json()); 
    //solution is below.. 
       private updateProduct(product: IProduct, options: RequestOptions):     Observable  {
       const url = `${this.baseUrl}/${product.id}`;
        let headers = new Headers();
        headers.append('Content-Type', 'application/json')
        return this._http.put(url, JSON.stringify(product), {headers: headers})
               .map(() => product)
               .do(data => console.log('updateProduct: ' + JSON.parse(JSON.stringify(data || null)) ))   
            .catch(this.handleError);
       } 
    //But I am unable to update any record....

2 个答案:

答案 0 :(得分:3)

RegularPrice排序并前6行。

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

这将为您提供价格最低的前六个记录。

答案 1 :(得分:1)

唯一合理的解释是,过滤后不会有6个项目。

如果过滤后有6个或更多项,则Take将为6。如果没有,它会留下什么。如果没有剩下,也可以返回空白集合。

哦和BTW,事先计算一下这条线。没用,评估每次迭代。

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