简体   繁体   English

如何在 lambda 表达式中写入 not in 子句,其中 not in 包含来自另一个 model 列表的值

[英]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.我正在尝试编写 lambda 表达式来获取其他 model 列表中存在 Id 的数据。 Below query returns the UserId which will be used further in anotherexpression as key to filter out the data.下面的查询返回 UserId,它将在另一个表达式中进一步用作过滤数据的键。

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"现在 _result 将具有 userId 属性,该属性将进一步用作过滤以下查询的数据的键,但是每当我尝试使用 User_id 过滤结果时,我在编译时遇到错误-“无法从字符串转换为 AccountDetail "

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

Note -AccountDetail is a model, below is model representation注意 -AccountDetail 是 model,下面是 model 表示

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.您需要将User_Id与列表中对象的属性值进行比较,而不是与列表中的对象进行比较。

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.如果结果包含 AccountDetails 列表,则 Contains 正在查找 AccountDetails object 而不是键。 You could use the.Any linq statement instead.您可以改用.Any linq 语句。 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或者创建字典或哈希集,而不是初始查询中的列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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