我正在尝试遍历字典列表中的不同值:
所以我有一个键值对字典。
如何从字典列表中获取字符串键的不同值?
var distinctList = mydict.Values.Distinct().ToList();
或者,您不需要调用 ToList():
foreach(var value in mydict.Values.Distinct())
{
// deal with it.
}
编辑:我误读了您的问题,并认为您想要字典中的不同值。上面的代码提供了这一点。
键是自动区分的。所以只需使用
foreach(var key in mydict.Keys)
{
// deal with it
}
字典中的键是不同的。根据定义。
所以myDict.Keys是一个不同的键列表。
循环不同的键并对每个值做一些事情......
foreach( dictionary.Keys )
{
// your code
}
如果您使用的是 C# 3.0 并且可以访问 LINQ:
只需获取一组不同的值:
// you may need to pass Distinct an IEqualityComparer<TSource>
// if default equality semantics are not appropriate...
foreach( dictionary.Values.Distinct() )
{
}
如果字典定义为:
Dictionary<string,MyType> theDictionary = ...
然后你可以使用
var distinctKeys = theDictionary.Keys;
这使用Dictionary.Keys属性。如果需要列表,可以使用:
var dictionaryKeysAsList = theDictionary.Keys.ToList();
由于它是字典,因此键已经是不同的。
如果您试图在字典中查找所有不同的值(与键相反 - 问题中并不清楚),您可以使用:
var distinctDictionaryValues = theDictionary.Values.Distinct(); // .ToList();