-3

I am trying to sum the "col3" values by ordering and grouping the "col1" and "col2" using C# Linq.

    List<dynamic> list = new List<dynamic>();

    dynamic expando = new ExpandoObject();
dynamic expando1 = new ExpandoObject();

    var p = expando as IDictionary<string, object>;

    p["col1"] = "New val 1";
    p["col2"] = "New val 2";
    p["col3"] = 20;

    list.Add(p);

    var q = expando1 as IDictionary<string, object>;

    q["col1"] = "New val 1";
    q["col2"] = "New val 3";
    q["col3"] = 10;

    list.Add(q);

I am trying to get the output as

New val 1

  • New val 2
  • New val 3

Total -- 30

Community
  • 1
  • 1

1 Answers1

0

What is the reason of creating ExpandoObject, but using it like a dictionary? If you know the set of the properties (col1, col2, col3) it would be better to create separate class for it, otherwise it could be done like this.

var list = new List<dynamic>();
dynamic e1 = new ExpandoObject();
e1.col1 = "New val 1";
e1.col2 = "New val 2";
e1.col3 = 20;
list.Add(e1);

dynamic e2 = new ExpandoObject();
e2.col1 = "New val 1";
e2.col2 = "New val 3";
e2.col3 = 10;
list.Add(e2);

foreach (var group in list
    .OrderBy(e => e.col1)
    .GroupBy(o => o.col1))
{
    Debug.WriteLine((string)group.Key);
    var sum = 0;
    foreach (var item in group)
    {
        Debug.WriteLine("    " + (string)item.col2);
        sum += item.col3;
    }

    Debug.WriteLine("Total: " + sum);
}
Valerii
  • 2,147
  • 2
  • 13
  • 27