gpt4 book ai didi

C# 从字典列表中获取所有键

转载 作者:行者123 更新时间:2023-12-05 08:45:16 27 4
gpt4 key购买 nike

我基本上想知道如何用 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());
}
}

谢谢。

最佳答案

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

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

关于C# 从字典列表中获取所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73296044/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com