Friday, 15 January 2010

c# - How to group data and store them in a new list by group -



c# - How to group data and store them in a new list by group -

how can store info in list group?

say,

public class productprice { public string name { get; set } public decimal cost { get; set; } // date , other properties }

then having record this:

+--------+--------+ | name | cost | +--------+--------+ | chair | 11 | | table | 15 | | table | 30 | | window | 24 | | chair | 29 | +--------+--------+

what should done in order accomplish list this:

{ { new productprice { name = "chair", cost = 11 }, new productprice { name = "chair", cost = 29 }, }, { new productprice { name = "table", cost = 15 }, new productprice { name = "table", cost = 30 } }, { new productprice { name = "window", cost = 24 } } }

as can see, grouped name , store them in list per group. great feed them a, say, line chart see cost trends. it's having hard time creating list.

in nutshell, can create list grouped products name? also, products can have new record well?

what need list<list<productprice>>, can do:

list<list<productprice>> groupedlist = list.groupby(r => r.name) .select(grp => new { list = grp.select(r => r).tolist() }) .select(r => r.list) .tolist();

this homecoming 3 values in list 1 each group.

you can project results dictionary<string, list<productprice>>, key name of product , value contain list<productprice> related key. utilize enumerable.todictionary like:

dictionary<string, list<productprice>> groupedlist = list.groupby(r => r.name) .todictionary(grp => grp.key, grp => grp.tolist());

c# linq

No comments:

Post a Comment