c# - 使用 lambda 表达式查找列表中的项目

标签 c# linq lambda

我有以下类(class):

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; }
}

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

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

但我遇到了错误:

Cannot implicitly convert type 'AuthenticatePromotion' to 'PromotionList'

我做错了什么?

最佳答案

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

var promotionList = AuthenticateCustomerResponse.EligiblePromotions.PromotionList
.Where(p => p.LineOfBusiness.ToUpper().Equals("VID")).FirstOrDefault();

如果您希望所有具有 VID 为 LineOfBusiness 而不是 .FirstOrDefault()

.ToList() >

编辑:如果要检查 SAT,可以在 .Where() 中添加另一个子句

关于c# - 使用 lambda 表达式查找列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929447/

相关文章:

c# - 尝试将我的 Web 应用程序从 VS Community 2015 发布到 Azure 时出错。错误: Can't find existing loaded project:http://localhost:55809

lambda - 我如何重写它以使用 lambda

c# - 这可以使用 lambda 以更少的代码完成吗?

python - Lambda 函数 - TypeError : unhashable type: 'numpy.ndarray'

c# - 如何将二维 JSON 数组发布到 Web 服务

c# - 安装后如何手动注册ClickOnce文件关联?

c# - 如何从(最初)大型对象列表中有效地过滤对象

c# - 如何正确使用 LINQ 和 MySQL?

c# - join和groupby后如何排序

c# - 为什么我的 linq 别名超出范围?