c# - LINQ how to use "group by" to simplify lists with duplicate attributes -
i have object "chartobject" , want group fields before can plot whole list.
public class chartobject { public string type { get; set; } public int year { get; set; } public long cost { get; set; } }
i want group type each year prevent duplicate types each year. each type want summed cost under year.
for example list:
chartobject(type1, 2015, $10)
chartobject(type1, 2015, $20)
chartobject(type2, 2016, $10)
chartobject(type1, 2016, $10)
chartobject(type2, 2017, $10)
chartobject(type2, 2017, $10)
should combined this:
chartobject(type1, 2015, $30)
chartobject(type1, 2016, $10)
chartobject(type2, 2016, $10)
chartobject(type2, 2017, $20)
this linq query have far. not correct since doesn't group year:
list<chartobject> colist = getitems(); var query = ( l in colist group l l.type x select new chartobject() { cost = x.sum(c => c.cost), type = x.first().type, year = x.first().year, } ).tolist();
the general approach follows:
// first groupby compound type .groupby(i => new { i.type, i.year }) // select group key , // apply aggregate/query on grouped values .select(g => new { type = g.key.type, // pull out key values year = g.key.year, cost = g.sum(i => i.cost) // sum items in group })
Comments
Post a Comment