使用lambda Expression查找计数

时间:2016-11-07 12:29:30

标签: c# linq lambda

我有以下课程:

public class Promotion
{
    public Offers Offers { get; set; }
}
public class Offers
{
   public List<PromotionOffer> Offer { get; set; }
}

public class PromotionOffer
{
    public string CategoryName { get; set; }
}

我的目标是Promotion

Promotion applicablePromotion = promotion;

applicablePromotion包含Offer列表,每个商品都有CategoryName。我想找到CategoryName == Package

的计数

类似的东西:

int count = applicablePromotion.Offers.Offer.Find(c => c.CategoryName == "Package").Count;

我该怎么做?

3 个答案:

答案 0 :(得分:3)

您可以使用:

var count = applicablePromotion.Offers.Offer.Count(o => o.CategoryName == "Package"); 

在LINQ中,Count可以接受Lambda表达式,您不必使用Where进行查询

在这里查看:

<iframe width="100%" height="475" src="https://dotnetfiddle.net/Widget/UKyWQJ" frameborder="0"></iframe>

答案 1 :(得分:2)

您可以使用Where代替Find

int count = applicablePromotion.Offers
       .Offer
       .Where(x=> x.CategoryName == "Package")
       .Count();

答案 2 :(得分:0)

不应该只是:

int count = applicablePromotion.Offers.Find(c => c.CategoryName == "Package").Count;

我认为Offers是你的集合,所以你必须运行Find。