2

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

1 Answer 1

7

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;
Sign up to request clarification or add additional context in comments.

2 Comments

What if I dont use ?. and just use . ?
@HumaAli Then in the case that no item was found you will get a NullReferenceException. Check link I gave about Null propagation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.