c# - How to convert database results to Dictionary<int, List<decimal>> -


we have table returns following rows:

id (integer)   price (decimal) 106                 5.2 106                 6.7 107                 9.2 107                 8.3 107                 3.2 

i need convert values table this:

106, (5.2, 6.7) 107, (9.2, 8.3, 3.2) 

in case dictionary<int, list<decimal>>, not have dictionary. can change it, if necessary.

number of id's , corresponding prices them not fixed (so can have 108 in list , can have 1 or more prices).

the following have done:

var retval = new dictionary<int, list<decimal>>(); var dbrow = new list<decimal>(); var itemsperrow = new list<list<decimal>>(); 

....

//loop table using (var dr = cmd.executereader()) {     while (dr.read())     {         dbrow.add(int.parse(dr["id"].tostring()));         dbrow.add(decimal.parse(dr["price"].tostring()));         itemsperrow.add(dbrow);     }         }  //get distinct id's  var gb = itemsperrow.groupby(x => x[0]).select(x => x.key);  foreach (var row in gb) {     if (!retval.containskey((int) row))     {         ienumerable<decimal> ratesforrow = itemsperrow.where(x => x.contains(row)).select(x => x[1]);         retval.add((int) row, ratesforrow.tolist());     } } 

this works seems not straight forward, not happy looping database results, creating list, looping list again, list declared contain decimals id column int, having cast int. ok, or there way of doing this?

thanks

you can directly in 1 loop:

  dictionary<int, list<decimal>> result = new dictionary<int, list<decimal>>();    using (var reader = cmd.executereader()) {     while (reader.read()) {       int id = int.parse(reader["id"].tostring());       decimal price = decimal.parse(reader["price"].tostring());        list<decimal> list;        if (result.trygetvalue(id, out list))             list.add(price);       else          result.add(id, new list<decimal> {price});     }   } 

Comments