如何获取所有父字典值的所有子字典元素的不同键
How to get Distinct keys of all child dictionary elements of all parent dictionary values
我有一本这样的字典...
Dictionary<string, Dictionary<string, double>>
如何从所有父字典值的所有字典中获取所有 Distinct
或 unique
子字典键的列表(父字典值只是子字典)?
在 C# 中执行此操作的最快方法是什么?
然后您需要在字典的 Values
属性 上调用 SelectMany()
,然后使用 Distinct()
通过默认相等比较器从序列中获取不同的元素.
var res = myDict.Values.SelectMany(x => x.Keys).Distinct().ToList();
使用 LINQ 真的很容易:
var result = myDict.Values.SelectMany(x => x.Keys)
.Concat(myDict.Keys)
.Distinct()
.ToList();
但即使没有 LINQ,使用 HashSet<string>
:
也非常容易
var set = new HashSet<string>();
foreach(var outerItem in myDict)
{
set.Add(outerItem.Key);
foreach(var innerKey in item.Value.Keys)
{
set.Add(innerKey);
}
}
HashSet<T>
只会保留不同的项目,因此两次添加相同的字符串不会有任何区别。
PS。下次你应该先尝试写代码,当你 运行 遇到你自己无法克服的问题时再问。 Stack Overflow 不是 'I want code, give me code' 那种网站。
此代码创建一个包含字符串键和双精度值的字典。
Dictionary<string, double> d = new Dictionary<string, double>()
{
};
// Store keys in a List
List<string> list = new List<string>(d.Keys);
// Loop through list
foreach (string k in list)
{
//From here you can choose distinct key
}
如果我没看错:
IEnumerable<string> uniqueChildKeys = dictOfDicts
.SelectMany(d => d.Value.Keys)
.Distinct();
我有一本这样的字典...
Dictionary<string, Dictionary<string, double>>
如何从所有父字典值的所有字典中获取所有 Distinct
或 unique
子字典键的列表(父字典值只是子字典)?
在 C# 中执行此操作的最快方法是什么?
然后您需要在字典的 Values
属性 上调用 SelectMany()
,然后使用 Distinct()
通过默认相等比较器从序列中获取不同的元素.
var res = myDict.Values.SelectMany(x => x.Keys).Distinct().ToList();
使用 LINQ 真的很容易:
var result = myDict.Values.SelectMany(x => x.Keys)
.Concat(myDict.Keys)
.Distinct()
.ToList();
但即使没有 LINQ,使用 HashSet<string>
:
var set = new HashSet<string>();
foreach(var outerItem in myDict)
{
set.Add(outerItem.Key);
foreach(var innerKey in item.Value.Keys)
{
set.Add(innerKey);
}
}
HashSet<T>
只会保留不同的项目,因此两次添加相同的字符串不会有任何区别。
PS。下次你应该先尝试写代码,当你 运行 遇到你自己无法克服的问题时再问。 Stack Overflow 不是 'I want code, give me code' 那种网站。
此代码创建一个包含字符串键和双精度值的字典。
Dictionary<string, double> d = new Dictionary<string, double>()
{
};
// Store keys in a List
List<string> list = new List<string>(d.Keys);
// Loop through list
foreach (string k in list)
{
//From here you can choose distinct key
}
如果我没看错:
IEnumerable<string> uniqueChildKeys = dictOfDicts
.SelectMany(d => d.Value.Keys)
.Distinct();