C#:从字典中删除重复值? [英] C#: Remove duplicate values from dictionary?

查看:73
本文介绍了C#:从字典中删除重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I create a dictionary with no duplicate values from a dictionary that may have duplicate values?

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.???

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

-I don't care which key is kept. - Is there something using Distinct() operation?

推荐答案

您想如何处理重复项?如果您不介意丢失哪个键,只需像这样构建另一个字典:

What do you want to do with the duplicates? If you don't mind which key you lose, just build another dictionary like this:

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);
    }
}

无可否认,这假定您使用的是 .NET 3.5.如果您需要 .NET 2.0 解决方案,请告诉我.

That assumes you're using .NET 3.5, admittedly. Let me know if you need a .NET 2.0 solution.

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

Here's a LINQ-based solution which I find pleasantly compact...

var uniqueValues = myDict.GroupBy(pair => pair.Value)
                         .Select(group => group.First())
                         .ToDictionary(pair => pair.Key, pair => pair.Value);

这篇关于C#:从字典中删除重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆