C#:从字典中删除重复值?

Use*_*ser 19 c# linq dictionary .net-3.5

如何从可能具有重复值的字典中创建没有重复值的字典?

IDictionary<string, string> myDict = new Dictionary<string, string>();

myDict.Add("1", "blue");
myDict.Add("2", "blue");
myDict.Add("3", "red");
myDict.Add("4", "green");


uniqueValueDict = myDict.???
Run Code Online (Sandbox Code Playgroud)

编辑:

- 我不在乎保留哪个键. - 是否有使用Distinct()操作的东西?

Jon*_*eet 49

你想用重复的东西做什么?如果您不介意丢失哪个密钥,只需构建另一个字典,如下所示:

IDictionary<string, string> myDict = new Dictionary<string, string>();

myDict.Add("1", "blue");
myDict.Add("2", "blue");
myDict.Add("3", "red");
myDict.Add("4", "green");

HashSet<string> knownValues = new HashSet<string>();
Dictionary<string, string> uniqueValues = new Dictionary<string, string>();

foreach (var pair in myDict)
{
    if (knownValues.Add(pair.Value))
    {
        uniqueValues.Add(pair.Key, pair.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

假设您正在使用.NET 3.5.如果您需要.NET 2.0解决方案,请告诉我.

这是一个基于LINQ的解决方案,我发现它非常紧凑......

var uniqueValues = myDict.GroupBy(pair => pair.Value)
                         .Select(group => group.First())
                         .ToDictionary(pair => pair.Key, pair => pair.Value);
Run Code Online (Sandbox Code Playgroud)

  • 在100K之后,他几乎没有知道它回到0,ruuhaha (10认同)

Dan*_*ner 7

蛮力解决方案将如下所示

var result = dictionary
    .GroupBy(kvp => kvp.Value)
    .ToDictionary(grp => grp.First().Value, grp.Key)
Run Code Online (Sandbox Code Playgroud)

假设您并不真正关心用于表示一组重复项的密钥,并且可以重建字典.