Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIND items in list using lambda expression

Tags:

c#

lambda

linq

I have following classes:

public class AuthenticateCustomerResponse
{
    public EligiblePromotions EligiblePromotions { get; set; }
}

public class EligiblePromotions
{
    public List<PromotionList> PromotionList { get; set; }
}
public class PromotionList
{
    public string LineOfBusiness { get; set; }
    public AuthenticatePromotions Promotions { get; set; }
}
public class AuthenticatePromotions
{
    public List<AuthenticatePromotion> Promotion { get; set; }
}
public class AuthenticatePromotion
{
    public string ServiceType { get; set; }
}

I want to retrieve PromotionList whose LineOfBusiness is equal to "VID" and ServiceType is equal to "SAT". I tried following lambda expression:

PromotionList getPromotion = AuthenticateCustomerResponse.EligiblePromotions.PromotionList.Find(p => p.LineOfBusiness.ToUpper().Equals("VID")).Promotions.Promotion.Find(o=>o.ServiceType.Equals("SAT"));

but I'm getting error:

Cannot implicitly convert type 'AuthenticatePromotion' to 'PromotionList'

What am I doing wrong?

like image 820
zaria khan Avatar asked May 10 '26 13:05

zaria khan


1 Answers

The code below will get you the first object whose LineOfBusiness equals to 'VID'.

var promotionList = AuthenticateCustomerResponse.EligiblePromotions.PromotionList
.Where(p => p.LineOfBusiness.ToUpper().Equals("VID")).FirstOrDefault();

You can use .ToList() if you want all objects that have VID as LineOfBusiness instead of .FirstOrDefault()

Edit: You can add another clause to your .Where() if you want to check for the SAT


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!