Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Dictionary has a Value in any of its Keys

So, I have a Dictionary and I need to check if in any of its Keys is there a certain Value present. As value, I use this class:

class Symbols
{
    public bool OPC { get; set; }

    public string Type { get; set; }
}

And, I am assigning the dictionary with the following key and values:

public static Dictionary<string, Symbols> SymbolDictionary = new Dictionary<string, Symbols>(StringComparer.CurrentCultureIgnoreCase);

Symbols symbol = new Symbols();

symbol.OPC = false;
symbol.Type = "Type";

SymbolDictionary.Add(Key,symbol);

If I check for SymbolDictionary[Key].symbol.OPC (or .symbol.Type) I get exactly the right values. But when I try to do this in a if, it never returns true:

if (SymbolDictionary.ContainsValue(symbol)) Console.WriteLine("Something");

As it never find a match of the values, even if I add the value and check it with the if statement right away. Any hints about how could I do that?

like image 907
Vinicius Silveira Avatar asked Jan 25 '26 06:01

Vinicius Silveira


2 Answers

That's because you haven't provided any comparison methods for your class.

The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparer that uses that implementation. Otherwise, it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

Some further reading:

  • Dictionary.ContainsValue Method
  • EqualityComparer.Default Property
  • Equality Comparisons (C# Programming Guide)
like image 51
decPL Avatar answered Jan 27 '26 20:01

decPL


TL;DR: your Symbols class must implement IEquatable<Symbols> in order for the comparison to work "as intended", or you must install a custom equality comparer when constructing the dictionary.

The ContainsValue method uses EqualityComparer<T>.Default as the method for comparing the specified value with the values in the dictionary for purposes of determining equality. If the class T does not implement IEquatable<T> then the default equality comparer uses reference equality; this means that this comparison won't work:

Symbols symbol1 = new Symbols();    
Symbols symbol2 = new Symbols();    
SymbolDictionary.Add("key", symbol1);
if (SymbolDictionary.ContainsValue(symbol2)) ... // false!

So first you must decide what "equal" means in the context of a symbol, and then implement the equality comparison accordingly. Make sure to read and heed the remarks in the IEquatable<T> documentation when implementing!

like image 25
Jon Avatar answered Jan 27 '26 18:01

Jon