sab669
sab669

Reputation: 4104

How to compare Dictionary<string, string[]>?

I found this post: Comparing 2 Dictionary<string, string> Instances

It's close enough to what I'm trying to do, so I thought it should work. I tried both the selected answer and the second answer and they both always return false in my case.

I'm trying to compare one pair of dictionaries and then the second pair. activeForm and activeFiles should be equal. archivedForm and archivedFiles should be equal.

enter image description here enter image description here


enter image description here enter image description here

Don't know what else I could try. Any ideas?

Upvotes: 0

Views: 1304

Answers (3)

Sky Fang
Sky Fang

Reputation: 1101

public class StringArrayEqualityComparer : IEqualityComparer<string[]>
{
    public bool Equals(string[] x, string[] y)
    {
        return x.OrderBy(z => z).SequenceEqual(y.OrderBy(z => z));
    }
    public int GetHashCode(string[] obj)
    {
        return obj.GetHashCode();
    }
}

You just need to implent IEqualityComparer<T>, then use the static method answered in Comparing 2 Dictionary<string, string> Instances

Upvotes: 3

shay__
shay__

Reputation: 3990

There are many ways of doing that. For example:

Dictionary exposes it's Keys as a collection. You can compare both keys collections first. If they are equal, iterate the dictionary and make sure the values are equal as well:

    private bool AreDictsEqual(IDictionary<string, string[]> d1, IDictionary<string, string[]> d2)
    {
        if (d1.Keys.OrderBy(p => p).SequenceEqual(d2.Keys.OrderBy(p => p)))
        {
            foreach (var item in d1)
            {
                if (!d2[item.Key].OrderBy(p => p).SequenceEqual(item.Value.OrderBy(p => p)))
                {
                    return false;
                }
            }
        }
        return false;
    }

There are more efficient ways of course, but that's just an example.

Upvotes: 1

Bsa0
Bsa0

Reputation: 2791

What is the code of the IEqualityComparer that compares the values? You need to compare each entry of both the arrays. Comparing the arrays directly will yield false since the references may be diferrent, even if the entries may be the same.

Upvotes: 0

Related Questions