1

So I have a dictionary (string, int> and I need to remove any entries in the dictionary that have duplicate values, except for the first entry So if you have;

dictionary<bob, 1>
dictionary<sam, 2>
dictionary<jack, 1>
dictionary<billy, 1>

Then both jack and billy would need to be removed while bob and sam would be kept.

Thank you for any assistance.

  • 5
    It is a dictionary, there is no _first_ or _second_ value. – Psi Mar 15 '17 at 23:14
  • its positioning in the Dictionary, I need to keep the first one that is entered into the dictionary and remove any that come after – Travis Jeffery Mar 15 '17 at 23:17
  • 3
    You aren't paying attention. In a dictionary, there is no such thing as the _"positioning"_, _"first"_ item, or _"any that come after"_. Dictionaries are unordered. The class provides no guarantee of ordering. So your problem statement makes no sense. If you are okay with _randomly_ selecting the one to keep, that's fine. See the answer given below. But otherwise, you need to state your question more clearly and specifically. – Peter Duniho Mar 15 '17 at 23:19
  • Your question is like an assignment. You should specify what you have done or are going to do, and what is your problem to do so. – Hamed Mar 15 '17 at 23:28

3 Answers3

1

Strictly, there is no first or second value, but if you just want to keep one value, no matter who the result would be, you can use a reversed dictionary to do that:

Dictionary<int,string> reverse = new Dictionary<int,string>();
foreach(string key in dictionary.Keys){
    if (reverse.ContainsKey( dictionary[key] ))
        continue;
    reverse.Add( dictionary[key], key );
}

Now your reverse dictionary has the value as its key (so it is unique) and one of the names attached to it (the name of the "first" occurence of that value). If you, however, do the same operation a second time, the results may differ, as there is no order in a dictionary at all.

Psi
  • 6,387
  • 3
  • 16
  • 26
1

In dictionary key-value pairs come in no specific order. If you are OK keeping an arbitrary one, you can do it with LINQ:

var first = dict
    .GroupBy(p => p.Value)
    .ToDictionary(g => g.First().Key, g => g.Key);
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

There's no way to tell from a dictionary which value was inserted first, because the key-value pairs aren't stored in any particular order. If you want to make sure that the values in a dictionary are unique, you would have to keep track of the values as you added them. The easiest way to do that would be with a HashSet. For example:

Dictionary<int, string> dictionary = new Dictionary<int, string>();
HashSet<string> values = new HashSet<string>();

...

public void AddToDictionary(int key, string value)
{
    if (values.Contains(value))
        return;

    dictionary.Add(key, value);
    values.Add(value);
}
Abion47
  • 22,211
  • 4
  • 65
  • 88