zaria khan
zaria khan

Reputation: 333

FIND items in list using lambda expression

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?

Upvotes: 3

Views: 19425

Answers (2)

Bassie
Bassie

Reputation: 10380

This part of your code

.Promotion.Find(o=>o.ServiceType.Equals("SAT"));

Returns an AuthenticatePromotion, but you are explicitly asking for a PromotionList object.

One way to get rid of the error would be to use the implicit variable keyword var:

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

But then this will of course still return an AuthenticatePromotion

Upvotes: 1

user4189129
user4189129

Reputation:

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

Upvotes: 8

Related Questions