C#: Remove duplicate values from dictionary?

前端 未结 8 2514
小蘑菇
小蘑菇 2020-12-09 03:28

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

IDictionary myDict = new Dicti         


        
相关标签:
8条回答
  • 2020-12-09 04:21

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

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

    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);
    
    0 讨论(0)
  • 2020-12-09 04:26

    This is how I did it:

                    dictionary.add(control, "string1");
                    dictionary.add(control, "string1");
                    dictionary.add(control, "string2");
                  int x = 0;
            for (int i = 0; i < dictionary.Count; i++)
            {         
                if (dictionary.ElementAt(i).Value == valu)
                {
                    x++;
                }
                if (x > 1)
                {
                    dictionary.Remove(control);
                }
            }
    
    0 讨论(0)
提交回复
热议问题