c# 4.0 - How to Use Distinct() and Sum() in Single Query in Linq -


here have 2 columns id,quantity. want distinct id , quantity sum in linq. tried

var r = list.where(some operation)             .select(x => x.id)             .distinct()             .select(x => (int?)x.quantity))             .sum(); 

here @ x.quantity got error..how can solve this.. please give suggestions

if assume id int , quantity string, can use aggregate also. below 1 example:

class testclass {     public int { get; set; }     public string s { get; set; } }  class program     {         static void main()         {             var myclass = new testclass[]             {                 new testclass {i = 1, s = "1"}, new testclass { = 1, s = "11" }, new testclass { = 1, s = "111" },                 new testclass {i = 2, s = "2"},new testclass {i = 2, s = "222"},new testclass {i = 2, s = "2"},                 new testclass {i = 3, s = "3"},new testclass {i = 3, s = "333"},new testclass {i = 3, s = "33"},                 new testclass {i = 4, s = "44"},new testclass {i = 4, s = "4"},                 new testclass {i = 5, s = "5"}             };              var filteredobject = myclass.groupby(x => x.i).select(y => new             {                 = y.key,                 s = y.select(z => z.s).aggregate((a, b) => (convert.toint32(a) + convert.toint32(b)).tostring())             });              filteredobject.tolist().foreach(x => console.writeline(x.i + "    " + x.s));         }      } 

result like:

1 123

2 226

3 369

4 48

5 5

press key continue . . .

hope helps.


Comments