C# Dictionary<TKey,TValue> 中的不同值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1155410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:32:43  来源:igfitidea点击:

Distinct Values in Dictionary<TKey,TValue>

c#.netlinqdistinct

提问by

I'm trying to loop over distinct values over a dictionary list:

我正在尝试通过字典列表遍历不同的值:

So I have a dictionary of key value pairs .

所以我有一个键值对字典。

How do I get just the distinct values of string keys from the dictionary list?

如何从字典列表中获取字符串键的不同值?

采纳答案by Randolpho

var distinctList = mydict.Values.Distinct().ToList();

Alternatively, you don't need to call ToList():

或者,您不需要调用 ToList():

foreach(var value in mydict.Values.Distinct())
{
  // deal with it. 
}

Edit:I misread your question and thought you wanted distinct values from the dictionary. The above code provides that.

编辑:我误读了您的问题,并认为您想要字典中的不同值。上面的代码提供了这一点。

Keys are automatically distinct. So just use

键是自动不同的。所以只需使用

foreach(var key in mydict.Keys)
{
  // deal with it
}

回答by LBushkin

Looping over distinct keys and doing something with each value...

循环不同的键并对每个值做一些事情......

foreach( dictionary.Keys )
{
    // your code
}

If you're using C# 3.0 and have access to LINQ:

如果您使用的是 C# 3.0 并且可以访问 LINQ:

Just fetching the set of distinct values:

只需获取一组不同的值:

// you may need to pass Distinct an IEqualityComparer<TSource>
// if default equality semantics are not appropriate...
foreach( dictionary.Values.Distinct() )
{
}

回答by Philippe Leybaert

Keys are distinct in a dictionary. By definition.

字典中的键是不同的。根据定义

So myDict.Keysis a distinct list of keys.

所以myDict.Keys是一个不同的键列表。

回答by Reed Copsey

If the dictionary is defined as:

如果字典定义为:

Dictionary<string,MyType> theDictionary =  ...

Then you can just use

然后你就可以使用

var distinctKeys = theDictionary.Keys;

This uses the Dictionary.Keysproperty. If you need a list, you can use:

这使用Dictionary.Keys属性。如果你需要一个列表,你可以使用:

var dictionaryKeysAsList = theDictionary.Keys.ToList();

Since it's a dictionary, the keys will already be distinct.

因为它是一本字典,所以键已经不同了。

If you're trying to find all of the distinct values (as opposed to keys - it wasn't clear in the question) in the dictionary, you could use:

如果您试图在字典中找到所有不同的值(而不是键 - 问题中不清楚),您可以使用:

var distinctDictionaryValues = theDictionary.Values.Distinct(); // .ToList();