I have a User called admin who has a list of Companys. 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. I don't really understand what the .Any() does but if I don't include it, the program has syntax errors. 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. The reason you need to override equals is because .Net doesn't know how to find equality in an object you created. 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.
EDIT 2: The Intersect Any is the way to go because you are want to compare a list to a list
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].
Where requires a boolean for the function evaluation. Give me the values in my list where the function given returns true. So when you give back [2,3] it complains. Any says are there any results in the list. so [2,3].Any() returns true, satisfying the Where.
Contains doesn't return the Intersection of the list, just tells you True of False, Does the value exist
Hope that helps.