c# - Perform Calculations Within List Using Linq and Lambda Expressions -
i have following object:
public class foo { public int32 id public int32 sampleid public int32 companyid public decimal data } public class bar { public int32 companyid public decimal data }
i have list of these objects. want perform calculation group ids "companyid" first. each company id, add 3 different sampleids data , returning new object each company.
//i want data sampleid = 2, 4 , 6 added //from foo object , put data of new bar object. list.groupby(l => l.companyid).select( x => new bar { companyid = x.key, ????? } );
i stuck how perform calculation after grouping. appreciated.
you pretty close me.
this should work:
var list = new list<foo> { new foo { companyid = 1, data = 15, id = 1, sampleid = 2 }, new foo { companyid = 1, data = 10, id = 2, sampleid = 4 }, new foo { companyid = 1, data = 25, id = 2, sampleid = 6 } }; var output = list.groupby( l => l.companyid, (key, data) => new bar { companyid = key, data = data.sum(d => d.data) });
or if want filter out 2,4,6 sample id (can't understand why honest) work:
[test] public void testing() { var list = new list<foo> { new foo { companyid = 1, data = 15, id = 1, sampleid = 2 }, new foo { companyid = 1, data = 10, id = 2, sampleid = 4 }, new foo { companyid = 1, data = 25, id = 3, sampleid = 8 }, new foo { companyid = 1, data = 25, id = 4, sampleid = 12 }, new foo { companyid = 1, data = 25, id = 5, sampleid = 14 } }; var filterlist = new list<int> { 2, 4, 6 }; var output = list.where(l => filterlist.contains(l.sampleid)) .groupby(l => l.companyid, (key, data) => new bar { companyid = key, data = data.sum(d => d.data) }); assert.true(output != null); assert.true(output.firstordefault() != null); assert.true(output.firstordefault().data == 25); }
Comments
Post a Comment