Find all items whose collection property contains items in another list

entity-framework linq

Question

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.

1
10
5/21/2013 12:39:37 AM

Accepted Answer

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.

16
5/21/2013 12:46:06 AM

Popular Answer

I've ended up implementing a helper method like this:

    public static bool HasElement<T>(ICollection<T> original, ICollection<T> otherCollection)
    {
        return original.Any(otherCollection.Contains);
    }

Hope it helps!



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow