【问题标题】:C# Multi-level dictionary.where finding resultsC# 多级字典.where 查找结果
【发布时间】:2020-11-19 14:10:55
【问题描述】:

我对 C# 还是很陌生,而且我到那里很慢,我已经搜索过但找不到任何东西,但我正在寻找一种方法来只获取具有相同标签的条目。

这是我的字典设置

public class CustomClass
{
    public string id { get; set; }
    public bool state { get; set; }
    public string data { get; set; }
}

public Dictionary<string, Dictionary<string, List<CustomClass>>> Status;

数据在 JSON 中的显示方式,我正在寻找的是一种仅获取我正在寻找的数据的有效方式。此 JSON 数据只是一个示例。

{
  "State1": {
    "Type1": [
      {
        "id": "UNIQUE ID 1",
        "state": true,
        "data": "DUMMY DATA"
      },
      {
        "id": "UNIQUE ID 2",
        "state": true,
        "data": "DUMMY DATA"
      }
    ],
    "Type2": []
  },
  "State2": {
    "Type1": [],
    "Type2": [
      {
        "id": "UNIQUE ID 1",
        "state": true,
        "data": "DUMMY DATA"
      },
      {
        "id": "UNIQUE ID 2",
        "state": false,
        "data": "DUMMY DATA"
      }
    ]
  }
}

我想做两件事,1 如果state 为真,则删除所有条目,我要寻找的另一件事是只获取state 为真的条目,我可以在其中阅读data 并使用它的价值。

基本上它有点像过期,如果state 为真,它不再相关意味着它应该被视为过期,这就是我需要阅读data 的原因,但我还需要一个选项来清除过期条目。

P.S:这本字典相当大,包含很多条目,这就是为什么我宁愿不做几个循环,就像我知道我可以做的那样。循环第一个字典,然后是第二个,然后是列表以查找哪些值。

【问题讨论】:

  • 你是如何将 Json 解析到班级的?好像不匹配

标签: c# list dictionary


【解决方案1】:

尝试以下:

            List<CustomClass> classes = new List<CustomClass>();
            Dictionary<string, Dictionary<string, List<CustomClass>>> Status = classes
                .Where(x => x.state == true)
                .GroupBy(x => x.id, y => y)
                .ToDictionary(x => x.Key, y => y.GroupBy(a => a.data, b => b)
                    .ToDictionary(a => a.Key, b => b.ToList()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2011-10-21
    • 2012-11-07
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多