简体   繁体   English

如何比较字典 <string, string[]> ?

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

I found this post: Comparing 2 Dictionary<string, string> Instances 我发现了这篇文章: 比较2 Dictionary <string,string>实例

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. 我尝试了选择的答案和第二个答案,在我的情况下,它们总是返回false。

I'm trying to compare one pair of dictionaries and then the second pair. 我正在尝试比较一对字典,然后比较第二对。 activeForm and activeFiles should be equal. activeForm和activeFiles应该相等。 archivedForm and archivedFiles should be equal. archivedForm和archivedFiles应该相等。

在此处输入图片说明在此处输入图片说明


在此处输入图片说明在此处输入图片说明

Don't know what else I could try. 不知道我还能尝试什么。 Any ideas? 有任何想法吗?

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 您只需要禁用IEqualityComparer<T>,然后使用比较2 Dictionary <string,string>实例中回答的静态方法

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. 当然,还有更有效的方法,但这只是一个例子。

What is the code of the IEqualityComparer that compares the values? 比较值的IEqualityComparer的代码是什么? 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. 直接比较数组将产生false,因为即使引用可能相同,引用也可能不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM