【问题标题】:C# Get all keys from a list of dictionariesC#从字典列表中获取所有键
【发布时间】:2022-08-14 03:21:28
【问题描述】:

我基本上想知道如何用 C# 编写这个 (Extract all keys from a list of dictionaries)。

我有一个包含所有唯一键的字典列表。

我想将它们全部提取到字符串列表中(因为键是字符串)。

private List<Dictionary<string, string>> dictList = new List<Dictionary<string, string>>
{
     new Dictionary<string, string>() { { \"a\", \"b\" } },
     new Dictionary<string, string>() { { \"c\", \"d\" } },
};

private void GetDictListKeys()
{
    List<string> keyList = new List<string>();
    foreach(var dict in dictList)
    {
        keyList.Add(dict.Keys.ToString());
    }
}

谢谢你。

    标签: c# list dictionary


    【解决方案1】:

    您想要展平您的可枚举键并将其转储到一个集合中(HashSet 使用是因为您提到了重复项,并且因为这也是您在 Python 中使用的链接答案):

    var allKeys = dictList.SelectMany(d => d.Keys).ToHashSet();
    

    【讨论】:

    • 如果您确实想要一个列表,请改用ToList()
    • ...或者如果您想要唯一键但列表使用dictList.SelectMany(d =&gt; d.Keys).Distinct().ToList()
    【解决方案2】:

    您可以使用 AddRange。

        foreach (var dict in dictList)
        {
            keyList.AddRange(dict.Keys);
        }
    

    【讨论】:

    • 另一种获得我想要的东西的好方法。谢谢!
    【解决方案3】:

    您可以在您的内部创建另一个 foreach 循环:

    foreach (Dictionary<string,string> dict in dictList)
    {
        foreach(string key in dict.Keys)
        {
            keyList.Add(key);                 
        }
    }
    

    【讨论】:

    • 真的无法想到有两个循环!非常感谢!
    猜你喜欢
    • 2019-08-09
    • 1970-01-01
    • 2014-11-27
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多