Thursday, 15 January 2015

c# - linq list of list sum of number -



c# - linq list of list sum of number -

i have code this(i have simplified real case)

public class { public list<b> list { get; set; } } public class b { public list<c> list{ get; set; } } public class c { public datetime date { get; set; } public int num { get; set; } }

i want sum num values date today. there error because have list(in class b) in list(in class a) how can do? try

a = new a(); b b1 = new b(); c c1 = new c() { date = datetime.today, num = 2 }; c c2 = new c() { date = datetime.today.adddays(1), num = 3 }; b1.list.add(c1); b1.list.add(c2); a.list.add(b1); b b2 = new b(); c c3 = new c() { date = datetime.today, num = 4 }; c c4 = new c() { date = datetime.today.adddays(1), num = 5 }; b2.list.add(c3); b2.list.add(c4); a.list.add(b2); var tot = (from l in a.list l.list.where(x => x.date == datetime.today) select l;

you can utilize selectmany outer list "flatten" inner ones, this:

var tot = a.list.selectmany(bitem => bitem.list) // point on, see "flat" ienumerable<c> .where(citem => citem.date == datetime.today) .sum(citem => citem.num);

c# linq

No comments:

Post a Comment