c# - Linq expression to filter an a list of entity's collection, and maintain list of entities -
lets 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 this: (assume list<foo>
)
// forget syntax, demonstrate data foo[0] = new foo{ id = 1, name = "a", bar = { collection of bars ages on 10 }}; foo[1] = new foo{ id = 2, name = "b", bar = { collection of bars ages on 20 }}; foo[2] = new foo{ id = 3, name = "c", bar = { collection of bars ages under 10 }};
now, lets wanted foo
s bar
s including bar
age between 5-25.
for this, work in reverse , bars, associated foos bars, , re-map bars foo. seems overly complicated should be.
to more clear - all foos bars ages between 5 , 25 :)
if want select foo
's , bar
's between age of 5 , 25:
var results = f in db.foos select new { f.id, f.name, bars = f.bars.where(b => b.age >= 5 && b.age <= 25) };
this produce anonymous type result. if need create named type (for example if need return result function list<t>
) should create simple named type result set:
public class foowithfilteredbarresult // replace whatever name { public long id { get; set; } public string name { get; set; } public ienumerable<bar> { get; set; } } list<foowithfilteredbarresult> results = (from f in db.foos select new foowithfilteredbarresult { id = f.id, name = f.name, bars = f.bars.where(b => b.age >= 5 && b.age <= 25) }) .tolist();
Comments
Post a Comment