用于查找属性的Lambda表达式

时间:2016-11-01 12:09:12

标签: c# linq lambda

我想从LineOfBusiness promotionCatalogResponseRootObject等于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);

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

select max(access_type) , owner from access group by owner

1 个答案:

答案 0 :(得分:7)

您遗漏的是Find方法期望接收带有bool返回值的谓词,但您返回的是string LineOfBusiness属性。

首先过滤所需的项目,然后选择所需的属性。另外,我使用的是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;