Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all items whose collection property contains items in another list

I have an collection of object Foo with an ICollection property containing a list of People objects.

public class Foo
{
  public int Id { get; set; }
  public string Name { get; set; }
  public ICollection<Person> People { get; set; }
}

I have another list of Person.

ICollection<Person> OtherPeople

I need to find all objects Foo where People contains any Person from OtherPeople. Is there a version of .Contains that accepts a collection? Something like:

var result = from f in FooCollection
             where f.People.Contains(otherPeople)
             select f;

I am using this with Entity Framework if that matters.

like image 849
Andrew Avatar asked May 21 '13 00:05

Andrew


1 Answers

Your referring to using C# Linq's Any method.

The Any method basically states if Any of the elements within that collection (Enumerable) satisfy a condition, in your case the condition is if another collection contains one of the elements.

ex.

public bool HasPeople(ICollection<Person> original, ICollection<Person> otherPeople)
{
    return original.Any(p => otherPeople.Contains(p));
}

However the Any method returns a boolean to state if the collection has Any elements that satisfy a condition - this doesn't give us which elements.

Another method in Linq that's worth noting is Where giving us all the elements that satisfy a condition.

ex.

public IEnumerable<Person> GetPeople(ICollection<Person> original, ICollection<Person> otherPeople)
{
    return original.Where(p => otherPeople.Contains(p));
}

I hope that gets you going in the right direction. Entity Framework shouldn't matter because they are Enumerable. Almost forgot to mention that the Linq methods are rather simple so theirs really no need for these to be in their own methods.

like image 123
Nate-Wilkins Avatar answered Sep 22 '22 14:09

Nate-Wilkins