c# - LINQ query string[] group by multiple anonymous columns -
i have delimited file reading string array (file has no headers) , trying parse linq query.
i want group multiple anonymous columns (using array indexes) , sum 1 of fields.
for instance, have file in format:
1000200034,2015,abc,1
1000200034,2015,def,2
i want group first , second columns, disregard third, , sum fourth.
so return:
1000200034,2015,3
when group single column, can result return sum:
ienumerable<string[]> query = row in data row[0] == "1000200034" group row row[0] g select new string[] { g.key, g.sum(a=>int.parse(a.elementat(3))).tostring(), };
but if try add other column, no longer sum, both rows returned:
ienumerable<string[]> query = row in data row[0] == "1000200034" group row new[]{row[0], row[1]} g select new string[] { g.key[0], g.key[1], g.sum(a=>int.parse(a.elementat(3))).tostring(), };
i'm pretty new linq , c#, sql background solid. having hard time converting know. appreciated!
the problem due grouping new []
should new
, have specify field names anonymous types used in group, like:
ienumerable<string[]> query = row in data row[0] == "1000200034" group row new { firstkey = row[0], secondkey = row[1] } g select new string[] { g.key.firstkey, g.key.secondkey, g.sum(a=>int.parse(a.elementat(3))).tostring(), };
with method syntax should like:
ienumerable<string[]> query2 = data.where(row => row[0] == "1000200034") .groupby(row => new { firstkey = row[0], secondkey = row[1] }) .select(grp => new string[] { grp.key.firstkey, grp.key.secondkey, grp.sum(a => int.parse(a.elementat(3))).tostring(), });
Comments
Post a Comment