简体   繁体   English

使用LINQ的两个列表的交集

[英]Intersection of two lists using LINQ

I have a User called admin who has a list of Companys. 我有一个名为admin的用户,该用户具有公司列表。 I want to return a list of Users who have one or more of the same Companys. 我想返回拥有一个或多个相同公司的用户列表。 I am using Linq using this query but I'm not sure why it is not working. 我正在使用Linq使用此查询,但是我不确定为什么它不起作用。 I don't really understand what the .Any() does but if I don't include it, the program has syntax errors. 我不太了解.Any()的功能,但是如果我不包含它,则程序会出现语法错误。 Here is my attempt: 这是我的尝试:

public List<User> GetUsers(User admin)
{
    return Users.Where(user=>user.Companys.Intersect(admin.Companys)).Any()).ToList();

}

EDIT: People in the comments are taking about overriding equals for your Company object and they are correct however we might be able to do something easier. 编辑:评论中的人正在为您的Company对象争取平等,他们是正确的,但是我们也许可以做一些容易的事情。 The reason you need to override equals is because .Net doesn't know how to find equality in an object you created. 需要覆盖equals的原因是因为.Net不知道如何在创建的对象中找到相等性。 so you would need to program in how to let it know. 因此您需要进行编程以使其了解。 It does know how to find equality in an ID most times however. 但是它确实知道如何在ID中找到相等性。

EDIT 2: The Intersect Any is the way to go because you are want to compare a list to a list 编辑2:相交是任何一种方式,因为您想将一个列表与一个列表进行比较

public List<User> GetUsers(User admin)
{
    var adminCompanyIDs = admin.Companys.Select(c => c.ID);
    return Users.Where(user=>user.Companys.Select(c => c.ID).Intersect(adminCompanyIDs).Any()).ToList();        
}

So Contains will search the list to see if any single value are in the list. 因此,包含将搜索列表以查看列表中是否有单个值。 Because it only searches for a single value it won't work for this. 由于它仅搜索单个值,因此不适用于该值。

Intersect will return the intersections of the two lists. 相交将返回两个列表的相交。 for example [1,2,3] [2,3,4] would give [2,3]. 例如[1,2,3] [2,3,4]将得出[2,3]。

Where requires a boolean for the function evaluation. where需要布尔值进行函数求值。 Give me the values in my list where the function given returns true. 给我列表中的值,其中给定的函数返回true。 So when you give back [2,3] it complains. 因此,当您退还[2,3]时会抱怨。 Any says are there any results in the list. 任何人说列表中有任何结果。 so [2,3].Any() returns true, satisfying the Where. 因此[2,3] .Any()返回true,满足Where。

Contains doesn't return the Intersection of the list, just tells you True of False, Does the value exist 包含不返回列表的交集,仅告诉您True为False,该值是否存在

Hope that helps. 希望能有所帮助。

try intersecting on a unique property instead of the object 尝试与唯一属性而不是对象相交

return Users.Where(user=>user.Companys.Select(c => c.ID).Intersect(admin.Companys.Select(a => a.id)).Any())
        .ToList();

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

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