Thursday, 8 August 2013

Linq expression to filter an a list of entity's collection?

Linq expression to filter an a list of entity's collection?

Lets say we have:
public class Foo
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<Bar> { get; set; }
}
public class Bar
{
public long Id { get; set; }
public int Age { get; set; }
public virtual Foo { get; set; }
public long FooId { get; set; }
}
Our data may look something like this: (assume List<Foo>)
// Forget the syntax, just to demonstrate data
foo[0] = new Foo{ Id = 1, Name = "A", Bar = { collection of Bars with Ages
over 10 }};
foo[1] = new Foo{ Id = 2, Name = "B", Bar = { collection of Bars with Ages
over 20 }};
foo[2] = new Foo{ Id = 3, Name = "C", Bar = { collection of Bars with Ages
under 10 }};
Now, lets say I wanted all those Foos but with their Bars only including a
Bar with an age between 5-25.
For something like this, I would work in reverse and get all Bars, then
get all associated Foos to those bars, and re-map the Bars back to Foo.
Seems overly complicated than it should be.

No comments:

Post a Comment