我有以下课程:
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;
我该怎么做?
答案 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。