C# LINQ 加入以查找不在列表中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/788485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ Join to find items NOT IN a list
提问by Craig McGuff
How do I use LINQ across Queryable and non-Queryable data?
如何跨可查询和不可查询数据使用 LINQ?
With the following code I want to end up with a list of unselected users, i.e. everyone in allUsers that is not in selected.
使用以下代码,我希望得到一个未选中用户列表,即所有用户中未选中的所有人。
public IQueryable<CompanyUser> FindAllUsersNotAssignedTothisCompany(int companyID)
{
var allUsers = Membership.GetAllUsers();
var selected = db.CompanyUsers.Where(c => c.CompanyID == companyID);
...?
}
I effectively want a list of User ID's and Names suitable for use in a DropDownList (ASP.NET MVC)
我实际上想要一个适用于 DropDownList (ASP.NET MVC) 的用户 ID 和名称列表
采纳答案by Jose Basilio
Assuming that both allUsers
and selected
are of the same type, You can do this using Except
假设两者allUsers
和selected
属于同一类型,您可以使用except来做到这一点
public IQueryable<CompanyUser> FindAllUsersNotAssignedTothisCompany(int companyID)
{
var allUsers = Membership.GetAllUsers();
var selected = db.CompanyUsers.Where(c => c.CompanyID == companyID);
return allUsers.Except(selected);
}
However if db.CompanyUsers already has all the users and all you need is to retrieve the users that do not have the companyID in question just:
但是,如果 db.CompanyUsers 已经拥有所有用户,而您所需要的只是检索没有相关 companyID 的用户:
return db.CompanyUsers.Where(c => c.CompanyID != companyID);
回答by Nalan Madheswaran
Try this in one line:
在一行中试试这个:
db.CompanyUsers.Where(c => !allUsers.Any(d=> d.CompanyID == a.companyID))).ToList();