Check identity dictionary

  • Thread starter Thread starter Luigi
  • Start date Start date
L

Luigi

Hi all,
I have a Dictionary (that is a property for a class) like this:

public Dictionary<string, decimal?> Value = new Dictionary<string,
decimal?>();

where I put the values like these:

column1 - 10
column2 - 12
....etc

When I chech to verify is two class are identical, the following code
returns me false, also if class "voce1" has "column1" and 10, like "voce2"

bool valoreUguale = (voce1.Value == voce2.Value);

Why this happen?

Thanks in advance.
 
Are you testing the two dictionaries for equality? If so, then it will
use the default = referential equality. i.e. are they *the same*
dictionary instance. In this case, no.

To check if the contents are equal you'd have to test each item in turn
(you can probably check the length first as a fast-fail) - something
like below.

Marc

static bool DictionaryEqual<TKey, TValue>(IDictionary<TKey,
TValue> left, IDictionary<TKey, TValue> right)
{
return DictionaryEqual<TKey, TValue>(left, right, null);
}
static bool DictionaryEqual<TKey, TValue>(IDictionary<TKey,
TValue> left, IDictionary<TKey, TValue> right, IEqualityComparer<TValue>
valueComparer)
{
if (ReferenceEquals(left, right)) return true;
if (left == null || right == null) return false;
if (left.Count != right.Count) return false;
if (valueComparer == null) valueComparer =
EqualityComparer<TValue>.Default;

foreach (KeyValuePair<TKey, TValue> pair in left)
{
TValue val;
if (!right.TryGetValue(pair.Key, out val) ||
!valueComparer.Equals(val, pair.Value)) return false;
}
return true;
}
 
Marc Gravell said:
Are you testing the two dictionaries for equality? If so, then it will
use the default = referential equality. i.e. are they *the same*
dictionary instance. In this case, no.

To check if the contents are equal you'd have to test each item in turn
(you can probably check the length first as a fast-fail) - something
like below.

Marc

static bool DictionaryEqual<TKey, TValue>(IDictionary<TKey,
TValue> left, IDictionary<TKey, TValue> right)
{
return DictionaryEqual<TKey, TValue>(left, right, null);
}
static bool DictionaryEqual<TKey, TValue>(IDictionary<TKey,
TValue> left, IDictionary<TKey, TValue> right, IEqualityComparer<TValue>
valueComparer)
{
if (ReferenceEquals(left, right)) return true;
if (left == null || right == null) return false;
if (left.Count != right.Count) return false;
if (valueComparer == null) valueComparer =
EqualityComparer<TValue>.Default;

foreach (KeyValuePair<TKey, TValue> pair in left)
{
TValue val;
if (!right.TryGetValue(pair.Key, out val) ||
!valueComparer.Equals(val, pair.Value)) return false;
}
return true;
}


Thank you Marc, now I try this snippet.

Luigi
 
Back
Top