使用 lambda 表达式在列表中查找项目

zar*_*han 3 c# linq lambda

我有以下课程:

public class AuthenticateCustomerResponse
{
    public EligiblePromotions EligiblePromotions { get; set; }
}

public class EligiblePromotions
{
    public List<PromotionList> PromotionList { get; set; }
}
public class PromotionList
{
    public string LineOfBusiness { get; set; }
    public AuthenticatePromotions Promotions { get; set; }
}
public class AuthenticatePromotions
{
    public List<AuthenticatePromotion> Promotion { get; set; }
}
public class AuthenticatePromotion
{
    public string ServiceType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想检索PromotionListLineOfBusiness等于“VID”且ServiceType等于“SAT”。我尝试了以下 lambda 表达式:

PromotionList getPromotion = AuthenticateCustomerResponse.EligiblePromotions.PromotionList.Find(p => p.LineOfBusiness.ToUpper().Equals("VID")).Promotions.Promotion.Find(o=>o.ServiceType.Equals("SAT"));
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

无法将类型“AuthenticatePromotion”隐式转换为“PromotionList”

我究竟做错了什么?

小智 7

下面的代码将为您提供第一个LineOfBusiness等于“VID”的对象。

var promotionList = AuthenticateCustomerResponse.EligiblePromotions.PromotionList
.Where(p => p.LineOfBusiness.ToUpper().Equals("VID")).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

您可以使用.ToList(),如果你想有VID为所有对象LineOfBusiness,而不是.FirstOrDefault()

编辑:.Where()如果您想检查 SAT,您可以添加另一个条款