带有列表和字典的元组对象

时间:2020-06-05 07:35:32

标签: c#-4.0 tuples

{
  "data": [
    {
      "id": 10,
      "title": "Administration",
      "active": true,
      "type": {
        "id": 2,
        "name": "Manager"
      }
    },
    {
      "id": 207,
      "title": "MCO - Exact Match 1",
      "active": true,
      "type": {
        "id": 128,
        "name": "Group"
      }
    },
    {
      "id": 1201,
      "title": "Regression",
      "active": false,
      "type": {
        "id": 2,
        "name": "Manager"
      }
    }
  ]
}

我正在尝试使用linq以以下格式创建元组。不知道如何从组/聚合开始。任何帮助表示赞赏。我遍历了几个线程,无法找到与此类似的内容。

var tuple = new List<Tuple<int, List<Dictionary<int,bool>>>();
                              2                10, true    
                                               1201, false
                              128              207,  true

1 个答案:

答案 0 :(得分:0)

这是完整的工作代码:

Last-Modified

这是它的工作方式:

  • If-None-Match是数据模型,使用匿名类型表示。显然,您可以在这里使用强类型模型(如果已有的话);
  • var o = new { data = new [] { new { id = 10, title = "Administration", active = true, type = new { id = 2, name = "Manager" } }, new { id = 207, title = "MCO - Exact Match 1", active = true, type = new { id = 128, name = "Group" } }, new { id = 1201, title = "Regression", active = false, type = new { id = 2, name = "Manager" } } } }; var result = o.data.GroupBy( item => item.type.id, // the group key item => new Dictionary<int, bool>() {{ item.id, item.active }}, // the transformed elements in the group (id, items) => new Tuple<int, List<Dictionary<int, bool>>>(id, items.ToList()) // transformation of grouping result to the final desired format ).ToList(); // check correctness foreach (var entry in result) { Console.Write(entry.Item1); foreach (var dict in entry.Item2) { foreach (var kvp in dict) Console.WriteLine("\t\t" + kvp.Key + "\t" + kvp.Value); } } 上,我们使用GroupBy的四参数版本,在official docs from Microsoft中进行了详细描述。基本上:
    • 第一个lambda表达式选择组密钥;
    • 第二个lambda定义每个组中的元素;
    • 第三个lambda将每个(组键,组元素的枚举)转换为o格式;
    • 最后,我们调用ToList()来计算结果并将其存储为元组列表。
  • 最后一部分显示结果(没有花很多时间来美化它,但是它确实在验证代码)。