Huma Ali Huma Ali - 1 month ago 8
C# Question

Lambda Expression for Finding properties

I want to retreive

LineOfBusiness
property from
promotionCatalogResponseRootObject
where
PromotionID
is equal to
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; }
}


I started off like this but I know I'm doing it wrong. Please guide

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

Answer

What you are missing is the the Find method is expecting to receive a predicate with a bool return value but you are returning a string, the LineOfBusiness property.

First filter the items you want and then select the desired property. In addition, I'd go with the Where instead of the Find. (Find() vs. Where().FirstOrDefault())

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

or in query syntax

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

If you are expecting/want to have one item then use FirstOrDefault:

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