Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
I have a List<dictionary<long,string>>(), and I know that some dictionaries in it are exactly the same. Does anyone know how to compare each dictionary to the other dictionaries in the list?

What I have tried:

I tried via:
C#
var listComplete = listDictionary.Distinct().ToList();

but unfortunately it was without result.

I know that a list that contains dictionaries should probably not be made, but I would be happy if someone could give me advice on this.

I would appreciate any advice and tips.

David
Posted
Updated 10-Nov-22 0:10am

You'll need to write an equality comparer:
C#
public sealed class DictionaryEqualityComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>>
{
    private readonly IEqualityComparer<TValue> _valueComparer;
    
    public DictionaryEqualityComparer(IEqualityComparer<TValue> valueComparer = null)
    {
        _valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
    }
    
    public bool Equals(IDictionary<TKey, TValue> left, IDictionary<TKey, TValue> right)
    {
        if (left is null) return right is null;
        if (right is null) return false;
        if (left.Count != right.Count) return false;
        
        foreach (KeyValuePair<TKey, TValue> pair in left)
        {
            if (!right.TryGetValue(pair.Key, out var value)) return false;
            if (!_valueComparer.Equals(pair.Value, value)) return false;
        }
        
        return true;
    }
    
    public int GetHashCode(IDictionary<TKey, TValue> obj)
    {
        // TODO: Improve the hashcode:
        return obj?.Count ?? 0;
    }
}
You would then need to use that class in your Distinct call:
C#
var equalityComparer = new DictionaryEqualityComparer<long, string>();
var listComplete = listDictionary.Distinct(equalityComparer).ToList();
 
Share this answer
 
Comments
dejf111 10-Nov-22 6:39am    
Thank you so much!
Google is your friend: compare 2 dictionaries c# - Google Search[^]

Here is one example: How to compare two dictionaries in C#?[^]

There are many more examples.
 
Share this answer
 
Comments
dejf111 10-Nov-22 5:29am    
I also found that, but I don't know how to take two dictionaries from the List (gradually to compare each with each)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900