简体   繁体   中英

How to write not in clause in lambda expression where not in contains value from another model list

I'm trying to write lambda expression to fetch data where Id is present in other model list. Below query returns the UserId which will be used further in anotherexpression as key to filter out the data.

var _result = authenticationStatus.accountDetails
.GroupBy(m => m.User_Id)
.Select(m =>new AccountDetails {
    User_Id= m.Key,
    IsReg = m.Sum(ta => Convert.ToInt32(ta.IsRegistered)) 
})
.Where(m => m.IsReg > 0)
.ToList();

Now _result will have userId property which will be further used as key to filter data for following query, but whenever I'm trying to use User_id to filter the result I'm getting an error at compile time -"cannot convert from string to AccountDetail"

var authenticated = authenticationStatus.accountDetails
                        .Where(x=>result.Contains(x.User_Id))
                        .ToList();

Note -AccountDetail is a model, below is model representation

public class AccountDetails
{
   public string UserId {get;set;}
   public int IsReg {get;set;}
}

You need to compare the User_Id to the property values of the objects in the list, not to the objects in the list.

var authenticated = authenticationStatus.accountDetails
    .Where(x => result.Any(y => y.UserId == x.User_Id))
    .ToList();

If result contains a List of AccountDetails, then Contains is looking for an AccountDetails object and not a key. You could use the.Any linq statement instead. Something like

var authenticated = authenticationStatus.accountDetails
.Where(x=>result.Any(ad = > string.Equals(ad.UserId, x.User_id))
.ToList();

Or create a Dictionary or a HashSet, not a list out of your initial query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM