Multi sums into one anonymous type with linq?

.net, c#, datatable, linq

Solution

Be dynamic:

dynamic result = new ExpandoObject();
dt.AsEnumerable()
  .GroupBy(r => r.Field<String>("type"))
  .ToList()
  .ForEach(g=> ((IDictionary<String, Object>)result)["sum" + g.Key.ToUpper()] = g.Sum(r=>r.Field<Int32>("cnt")));

Console.WriteLine(result.sumAAA);
Console.WriteLine(result.sumBBB);

Works for a arbitary number of different `type`s, not only `aaa` and `bbb`.

Output:

13 2

Problem

I have this simple datatable : ``` type (string) | cnt (int) _____________________________________ aaa 1 aaa 2 aaa 10 bbb 1 bbb 1 ``` I want to produce 1 anonymous type like this : ``` { sumAAA= 13 , sumBBB=2 //13=1+2+10.... } ``` something like : (psuedo code ) ``` var obj= dt.AsEnumerable().Select(f=> new { sumAAA =f.sumOfCntOfAaa , sumBBB =f.sumOfCntOfBbb }); ``` any help ? edit , this will help you ``` DataTable dt = new DataTable("myTable"); dt.Columns.Add("cnt", typeof (int)); dt.Columns.Add("type", typeof (string)); DataRow row = dt.NewRow(); row["cnt"] = 1; row["type"] = "aaa"; dt.Rows.Add(row); row = dt.NewRow(); row["cnt"] = 2; row["type"] = "aaa"; dt.Rows.Add(row); row = dt.NewRow(); row["cnt"] = 10; row["type"] = "aaa"; dt.Rows.Add(row); row = dt.NewRow(); row["cnt"] = 1; row["type"] = "bbb"; dt.Rows.Add(row); row = dt.NewRow(); row["cnt"] = 1; row["type"] = "bbb"; dt.Rows.Add(row); ```

Original source

Related problems