ExpandoObject c# 中数组的排序、分组和求和列表

Order,group and sum List of array in ExpandoObject c#

我试图通过使用 C# Linq 对“col1”和“col2”进行排序和分组来对“col3”值求和。

    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);

我正在尝试将输出设为

New val 1

  • New val 2
  • New val 3

Total -- 30

为什么创建了ExpandoObject,却像字典一样使用它?如果您知道属性集 (col1, col2, col3),最好为它创建单独的 class,否则可以这样做。

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);
}