![](/img/trans.png)
[英]ConcurrentDictionary<TKey,TValue> vs Dictionary<TKey,TValue>
[英]Distinct Values in Dictionary<TKey,TValue>
我試圖在字典列表上循環不同的值:
所以我有一個關鍵值對字典。
如何從字典列表中獲取字符串鍵的不同值?
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.