c# - LINQ Sum all properties -
is there elegant way this?
assume working objects have excusively numeric properties (ints , doubles), this:
foo -bar1 int -bar2 int -bar3 int -foobar1 double -foobar2 double
and have collection of list...is there way have sum numeric properties in list , return single object foo totals?
thanks so
it can done using one-liner :-)
item sum = (from p in typeof(item).getfields() type.gettypecode(p.fieldtype) == typecode.int32 || type.gettypecode(p.fieldtype) == typecode.double group p p g select new { prop=g.key, sum=items.sum(s => (decimal)convert.changetype(g.key.getvalue(s), typecode.decimal)) }) .aggregate(new item(), (state, next) => { next.prop.setvalue(state, convert.changetype(next.sum, next.prop.fieldtype)); return state; });
complete sample:
using system; using system.linq; using system.collections.generic; class program { class item { public int bar1 = 0; public int bar2 = 0; public double foobar1 = 0; public double foobar2 = 0; } public static void main () { var items = new list<item>(); items.add(new item() { bar1 = 1, bar2 = 2, foobar1 = 1.1, foobar2 = 1.2 }); items.add(new item() { bar1 = 1, bar2 = 2, foobar1 = 1.1, foobar2 = 1.2 }); items.add(new item() { bar1 = 1, bar2 = 2, foobar1 = 1.1, foobar2 = 1.2 }); var sum = (from p in typeof(item).getfields() type.gettypecode(p.fieldtype) == typecode.int32 || type.gettypecode(p.fieldtype) == typecode.double group p p g select new { prop=g.key, sum=items.sum(s => (decimal)convert.changetype(g.key.getvalue(s), typecode.decimal)) }) .aggregate(new item(), (state, next) => { next.prop.setvalue(state, convert.changetype(next.sum, next.prop.fieldtype)); return state; }); console.writeline("bar1: " + sum.bar1); console.writeline("bar2: " + sum.bar2); console.writeline("foobar1: " + sum.foobar1); console.writeline("foobar2: " + sum.foobar2); } }
Comments
Post a Comment