【问题标题】:Lambda Expression for Finding properties用于查找属性的 Lambda 表达式
【发布时间】:2016-11-01 12:09:11
【问题描述】:

我想从promotionCatalogResponseRootObject 检索LineOfBusiness 属性,其中PromotionID 等于myId

public class PromotionCatalogResponseRootObject
{
   public PromotionCatalogResponse PromotionCatalog { get; set; }
}

public class Promotion
{
  public string PromotionId { get; set; }
  public string LineOfBusiness { get; set; }
  public string PromotionName { get; set; }
}

public class PromotionCatalogResponse
{
  public List<Promotion> Promotion { get; set; }
}

我一开始就是这样,但我知道我做错了。请指导

string myId = "7596";
string lineOfBusiness = dataPromotionCatalog.PromotionCatalog
                                            .Promotion.Find(p => p.LineOfBusiness);

【问题讨论】:

    标签: c# linq lambda


    【解决方案1】:

    您缺少的是Find 方法期望接收具有bool 返回值的谓词,但您返回的是stringLineOfBusiness 属性。

    首先过滤您想要的项目,然后选择所需的属性。此外,我会选择Where 而不是Find。 (Find() vs. Where().FirstOrDefault())

    var result = dataPromotionCatalog.PromotionCatalog.Promotion
                                     .Where(i => i.PromotionId == myId)
                                     .Select(i => i.LineOfBusiness);
    

    或在查询语法中

    var result = (from item in dataPromotionCatalog.PromotionCatalog.Promotion
                  where item.PromotionId == myId
                  select item.LineOfBusiness);
    

    如果您期待/想要拥有一件商品,请使用FirstOrDefault

    var result = dataPromotionCatalog.PromotionCatalog.Promotion
                     .FirstOrDefault(i => i.PromotionId == myId)?.LineOfBusiness;
    

    【讨论】:

    • 如果我不使用?.而只使用.怎么办?
    • @HumaAli 如果没有找到任何项目,您将获得NullReferenceException。检查我给的关于Null propagation的链接
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    相关资源
    最近更新 更多