Home > Net >  How to compare and select particular object from list using LINQ
How to compare and select particular object from list using LINQ

Time:12-08

I've two set of list of objects. One named as SellWish and another as holdingAdviceDecisions. These two objects are linked via two items such as: SellWishId and HoldingAdviceId

I'm trying to get the matched values between these with the following condition

 holdingAdvice.CustomerDecision == CustomerDecision.FollowsAdvice 

This is what I've tried so far:

var item = sellWishes.Where(sellWish =>
 holdingAdviceDecisions.Where
 (holdingAdvice => sellWish.Id == holdingAdvice.TradeInstructionId
      && holdingAdvice.CustomerDecision == CustomerDecision.FollowsAdvice));

But I'm getting following errors:

  1. Error CS1662
    Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

2.Error CS0029
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<HoldingsAdvice.Contracts.HoldingAdviceDecision>' to 'bool'

Any suggestion would be highly appreciated.

CodePudding user response:

you need

var items = sellWishes.Where(sellWish =>
  holdingAdviceDecisions.Any
    (holdingAdvice => sellWish.Id == holdingAdvice.TradeInstructionId
   && holdingAdvice.CustomerDecision == CustomerDecision.FollowsAdvice));

note that this reurns all matching entries, if you know you only the first (or null)

 var item = sellWishes.Where(sellWish =>
        holdingAdviceDecisions.Any
  (holdingAdvice => sellWish.Id == holdingAdvice.TradeInstructionId
    && holdingAdvice.CustomerDecision == CustomerDecision.FollowsAdvice)).FirstOrDefault();
  • Related