【问题标题】:Get All instead of FirstOrDefault获取全部而不是 FirstOrDefault
【发布时间】:2016-12-02 11:46:32
【问题描述】:

我有以下疑问:

PromotionList dataPromotion = authenticateCustomerResponseRootObject.Response
    .AuthenticateCustomerResponse.EligiblePromotions.PromotionList
    .Where(p => p.LineOfBusiness.ToUpper().Equals("DATA"))
    .FirstOrDefault();

我的 PromotionList 包含 3 个对象,LineOfBusiness Data,Video 和第三个对象也包含 Data。上面的查询仅返回第一个对象的PromotionList,而我想要所有 LineOfBusiness 等于数据的对象。为什么会这样?

【问题讨论】:

  • 因为查询中最后一个方法是.FirstOrDefault()?
  • 嗯,如果你想要所有对象,那你为什么要FirstOrDefault()呢?去掉那个电话,这不就是你想要的吗???
  • 嗯。因为你明确使用了FirstOrDefault?

标签: c# linq lambda


【解决方案1】:

您正在使用FirstOrDefault,因此您只返回第一个。

PromotionList dataPromotion = authenticateCustomerResponseRootObject.Response.AuthenticateCustomerResponse.EligiblePromotions.PromotionList.Where(p => p.LineOfBusiness.ToUpper().Equals("Data")).FirstOrDefault();

如果您想要所有这些,只需在最后删除该调用并替换为满足您需求的 ToListToArray 或类似名称:

var data = authenticateCustomerResponseRootObject.Response.AuthenticateCustomerResponse.EligiblePromotions.PromotionList.Where(p => p.LineOfBusiness.ToUpper().Equals("Data")).ToList();

正如 cmets 中提到的,您的 Where 调用使用 ToUpper 然后比较包含小写字符的字符串,因此永远不会返回任何结果。您要么需要删除ToUpper,使用大写字符串,甚至使用忽略大小写:

Where(p => p.LineOfBusiness.Equals("Data", StringComparison.OrdinalIgnoreCase))   

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 2020-03-29
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多