是否有一个内置的方法来比较集合?

时间:2023-01-15 21:45:53

I would like to compare the contents of a couple of collections in my Equals method. I have a Dictionary and an IList. Is there a built-in method to do this?

我想比较一下Equals方法中两个集合的内容。我有一本字典和一本《伊利亚特》。有内置的方法可以做到这一点吗?

Edited: I want to compare two Dictionaries and two ILists, so I think what equality means is clear - if the two dictionaries contain the same keys mapped to the same values, then they're equal.

编辑:我想比较两本字典和两本《伊利亚特》,所以我认为平等的含义是明确的——如果这两本字典包含映射到相同值的相同键,那么它们是相等的。

13 个解决方案

#1


156  

Enumerable.SequenceEqual

Enumerable.SequenceEqual

Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer(T).

通过使用指定的IEqualityComparer(T)比较两个序列的元素来确定它们是否相等。

You can't directly compare the list & the dictionary, but you could compare the list of values from the Dictionary with the list

您不能直接比较列表和字典,但是可以将字典中的值列表与列表中的值进行比较

#2


36  

As others have suggested and have noted, SequenceEqual is order-sensitive. To solve that, you can sort the dictionary by key (which is unique, and thus the sort is always stable) and then use SequenceEqual. The following expression checks if two dictionaries are equal regardless of their internal order:

正如其他人所指出并指出的,顺序平等是对订单敏感的。要解决这个问题,您可以按键对字典进行排序(这是惟一的,因此排序总是稳定的),然后使用SequenceEqual。下面的表达式检查两个字典是否相等,不管它们的内部顺序是什么:

dictionary1.OrderBy(kvp => kvp.Key).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key))

EDIT: As pointed out by Jeppe Stig Nielsen, some object have an IComparer<T> that is incompatible with their IEqualityComparer<T>, yielding incorrect results. When using keys with such an object, you must specify a correct IComparer<T> for those keys. For example, with string keys (which exhibit this issue), you must do the following in order to get correct results:

编辑:正如Jeppe Stig Nielsen所指出的,有些对象有一个IComparer ,它与它们的IEqualityComparer 不兼容,产生不正确的结果。当使用此类对象的键时,必须为这些键指定正确的IComparer 。例如,使用string键(显示这个问题),您必须执行以下操作才能得到正确的结果:

dictionary1.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key, StringComparer.Ordinal))

#3


13  

In addition to the mentioned SequenceEqual, which

除了前面提到的顺序相等之外

is true if two lists are of equal length and their corresponding elements compare equal according to a comparer

如果两个列表的长度相等,并且它们对应的元素按照比较器进行比较,是否正确

(which may be the default comparer, i.e. an overriden Equals())

(可能是默认比较器,即overriden Equals()))

it is worth mentioning that in .Net4 there is SetEquals on ISet objects, which

值得一提的是,在。net4中,ISet对象上有SetEquals。

ignores the order of elements and any duplicate elements.

忽略元素的顺序和任何重复的元素。

So if you want to have a list of objects, but they don't need to be in a specific order, consider that an ISet (like a HashSet) may be the right choice.

因此,如果您想要一个对象列表,但是它们不需要按特定的顺序排列,可以考虑使用ISet(比如HashSet)可能是正确的选择。

#4


8  

Take a look at the Enumerable.SequenceEqual method

看看可数名词。SequenceEqual方法

var dictionary = new Dictionary<int, string>() {{1, "a"}, {2, "b"}};
var intList = new List<int> {1, 2};
var stringList = new List<string> {"a", "b"};
var test1 = dictionary.Keys.SequenceEqual(intList);
var test2 = dictionary.Values.SequenceEqual(stringList);

#5


5  

I didn't know about Enumerable.SequenceEqual method (you learn something every day....), but I was going to suggest using an extension method; something like this:

我不知道可枚举。SequenceEqual方法(你每天都学习一些....),但我建议使用一个扩展方法;是这样的:

    public static bool IsEqual(this List<int> InternalList, List<int> ExternalList)
    {
        if (InternalList.Count != ExternalList.Count)
        {
            return false;
        }
        else
        {
            for (int i = 0; i < InternalList.Count; i++)
            {
                if (InternalList[i] != ExternalList[i])
                    return false;
            }
        }

        return true;

    }

Interestingly enough, after taking 2 seconds to read about SequenceEqual, it looks like Microsoft has built the function I described for you.

有趣的是,在花了2秒钟阅读了SequenceEqual之后,看起来微软已经构建了我为您描述的功能。

#6


5  

.NET Lacks any powerful tools for comparing collections. I've developed a simple solution you can find at the link below:

. net缺乏任何比较集合的强大工具。我开发了一个简单的解决方案,你可以在下面的链接中找到:

http://robertbouillon.com/2010/04/29/comparing-collections-in-net/

http://robertbouillon.com/2010/04/29/comparing-collections-in-net/

This will perform an equality comparison regardless of order:

这将执行平等比较,不管顺序:

var list1 = new[] { "Bill", "Bob", "Sally" };
var list2 = new[] { "Bob", "Bill", "Sally" };
bool isequal = list1.Compare(list2).IsSame;

This will check to see if items were added / removed:

这将检查项目是否被添加/删除:

var list1 = new[] { "Billy", "Bob" };
var list2 = new[] { "Bob", "Sally" };
var diff = list1.Compare(list2);
var onlyinlist1 = diff.Removed; //Billy
var onlyinlist2 = diff.Added;   //Sally
var inbothlists = diff.Equal;   //Bob

This will see what items in the dictionary changed:

这将会看到字典里的条目发生了什么变化:

var original = new Dictionary<int, string>() { { 1, "a" }, { 2, "b" } };
var changed = new Dictionary<int, string>() { { 1, "aaa" }, { 2, "b" } };
var diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);
foreach (var item in diff.Different)
  Console.Write("{0} changed to {1}", item.Key.Value, item.Value.Value);
//Will output: a changed to aaa

#7


3  

This is not directly answering your questions, but both the MS' TestTools and NUnit provide

这并不是直接回答您的问题,而是MS的TestTools和NUnit提供的

 CollectionAssert.AreEquivalent

which does pretty much what you want.

这基本上就是你想要的。

#8


1  

To compare collections you can also use LINQ. Enumerable.Intersect returns all pairs that are equal. You can comparse two dictionaries like this:

要比较集合,还可以使用LINQ。可列举的。Intersect返回所有相等的对。你可以像这样比较两本字典:

(dict1.Count == dict2.Count) && dict1.Intersect(dict2).Count() == dict1.Count

The first comparison is needed because dict2 can contain all the keys from dict1 and more.

需要进行第一次比较,因为dict2可以包含来自dict1及更多版本的所有键。

You can also use think of variations using Enumerable.Except and Enumerable.Union that lead to similar results. But can be used to determine the exact differences between sets.

您还可以使用枚举的变体来考虑变量。除了和枚举。这导致了类似的结果。但是可以用来确定集合之间的确切区别。

#9


1  

How about this example:

这个例子:

 static void Main()
{
    // Create a dictionary and add several elements to it.
    var dict = new Dictionary<string, int>();
    dict.Add("cat", 2);
    dict.Add("dog", 3);
    dict.Add("x", 4);

    // Create another dictionary.
    var dict2 = new Dictionary<string, int>();
    dict2.Add("cat", 2);
    dict2.Add("dog", 3);
    dict2.Add("x", 4);

    // Test for equality.
    bool equal = false;
    if (dict.Count == dict2.Count) // Require equal count.
    {
        equal = true;
        foreach (var pair in dict)
        {
            int value;
            if (dict2.TryGetValue(pair.Key, out value))
            {
                // Require value be equal.
                if (value != pair.Value)
                {
                    equal = false;
                    break;
                }
            }
            else
            {
                // Require key be present.
                equal = false;
                break;
            }
        }
    }
    Console.WriteLine(equal);
}

Courtesy : https://www.dotnetperls.com/dictionary-equals

礼貌:https://www.dotnetperls.com/dictionary-equals

#10


0  

No. The collection framework doesn't have any concept of equality. If you think about it there is no way of comparing collections which isn't subjective. For instance comparing your IList to your Dictionary, would they be equal if all the keys were in the IList, all the values were in the IList or if both were in the IList? There is no obvious way of comparing these two collections without knowledge of what they are to be used for so a general purpose equals method makes no sense.

不。集合框架没有任何平等的概念。如果你仔细想想,就会发现没有一种方法可以比较非主观的集合。比如比较你的《伊利亚特》和你的字典,如果所有的键都在《伊利亚特》中,所有的值都在《伊利亚特》中,或者两者都在《伊利亚特》中,它们会相等吗?没有明显的方法来比较这两个集合而不知道它们是用来做什么的,所以一个通用的目的等于方法是没有意义的。

#11


0  

No, because the framework doesn't know how to compare the contents of your lists.

不,因为框架不知道如何比较列表的内容。

Have a look at this:

看看这个:

http://blogs.msdn.com/abhinaba/archive/2005/10/11/479537.aspx

http://blogs.msdn.com/abhinaba/archive/2005/10/11/479537.aspx

#12


0  

public bool CompareStringLists(List<string> list1, List<string> list2)
{
    if (list1.Count != list2.Count) return false;

    foreach(string item in list1)
    {
        if (!list2.Contains(item)) return false;
    }

    return true;
}

#13


0  

There wasn't, isn't and might not be, at least I would believe so. The reason behind is collection equality is probably an user defined behavior.

没有,没有,也可能没有,至少我相信是这样。原因是集合相等性可能是用户定义的行为。

Elements in collections are not supposed to be in a particular order though they do have an ordering naturally, it's not what the comparing algorithms should rely on. Say you have two collections of:

集合中的元素不应该按照特定的顺序排列,尽管它们具有自然的顺序,但这不是比较算法应该依赖的。假设你有两个集合:

{1, 2, 3, 4}
{4, 3, 2, 1}

Are they equal or not? You must know but I don't know what's your point of view.

它们是否相等?你必须知道,但我不知道你的观点是什么。

Collections are conceptually unordered by default, until the algorithms provide the sorting rules. The same thing SQL server will bring to your attention is when you trying to do pagination, it requires you to provide sorting rules:

默认情况下,集合在概念上是无序的,直到算法提供排序规则为止。同样的SQL server也会引起你的注意,当你试图进行分页时,它需要你提供排序规则:

https://docs.microsoft.com/en-US/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-2017

https://docs.microsoft.com/en - us/sql/t sql/queries/select秩序——通过条款-处理- sql?view=sql -服务器- 2017

Yet another two collections:

另一个两个集合:

{1, 2, 3, 4}
{1, 1, 1, 2, 2, 3, 4}

Again, are they equal or not? You tell me ..

同样,它们是否相等?你告诉我. .

Element repeatability of a collection plays its role in different scenarios and some collections like Dictionary<TKey, TValue> don't even allow repeated elements.

集合的元素可重复性在不同的场景中扮演着重要的角色,有些集合如Dictionary 甚至不允许重复元素。 ,>

I believe these kinds of equality are application defined and the framework therefore did not provide all of the possible implementations.

我认为这些平等是定义好的应用程序,因此框架没有提供所有可能的实现。

Well, in general cases Enumerable.SequenceEqual is good enough but it returns false in the following case:

一般情况下是可列举的。SequenceEqual足够好,但在以下情况下返回false:

var a = new Dictionary<String, int> { { "2", 2 }, { "1", 1 }, };
var b = new Dictionary<String, int> { { "1", 1 }, { "2", 2 }, };
Debug.Print("{0}", a.SequenceEqual(b)); // false

I read some answers to questions like this(you may google for them) and what I would use, in general:

我读了一些这样的问题的答案(你可以用谷歌来回答),我一般会用些什么:

public static class CollectionExtensions {
    public static bool Represents<T>(this IEnumerable<T> first, IEnumerable<T> second) {
        if(object.ReferenceEquals(first, second)) {
            return true;
        }

        if(first is IOrderedEnumerable<T> && second is IOrderedEnumerable<T>) {
            return Enumerable.SequenceEqual(first, second);
        }

        if(first is ICollection<T> && second is ICollection<T>) {
            if(first.Count()!=second.Count()) {
                return false;
            }
        }

        first=first.OrderBy(x => x.GetHashCode());
        second=second.OrderBy(x => x.GetHashCode());
        return CollectionExtensions.Represents(first, second);
    }
}

That means one collection represents the other in their elements including repeated times without taking the original ordering into account. Some notes of the implementation:

这意味着一个集合在其元素中表示另一个集合,包括重复的次数,而没有考虑原始排序。执行情况的一些说明:

  • GetHashCode() is just for the ordering not for equality; I think it's enough in this case

    GetHashCode()只是用于排序而不是用于平等;我认为在这种情况下已经足够了

  • Count() will not really enumerates the collection and directly fall into the property implementation of ICollection<T>.Count

    Count()不会真正枚举集合,直接属于ICollection .Count .Count的属性实现

  • If the references are equal, it's just Boris

    如果引用是相等的,那就是Boris

#1


156  

Enumerable.SequenceEqual

Enumerable.SequenceEqual

Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer(T).

通过使用指定的IEqualityComparer(T)比较两个序列的元素来确定它们是否相等。

You can't directly compare the list & the dictionary, but you could compare the list of values from the Dictionary with the list

您不能直接比较列表和字典,但是可以将字典中的值列表与列表中的值进行比较

#2


36  

As others have suggested and have noted, SequenceEqual is order-sensitive. To solve that, you can sort the dictionary by key (which is unique, and thus the sort is always stable) and then use SequenceEqual. The following expression checks if two dictionaries are equal regardless of their internal order:

正如其他人所指出并指出的,顺序平等是对订单敏感的。要解决这个问题,您可以按键对字典进行排序(这是惟一的,因此排序总是稳定的),然后使用SequenceEqual。下面的表达式检查两个字典是否相等,不管它们的内部顺序是什么:

dictionary1.OrderBy(kvp => kvp.Key).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key))

EDIT: As pointed out by Jeppe Stig Nielsen, some object have an IComparer<T> that is incompatible with their IEqualityComparer<T>, yielding incorrect results. When using keys with such an object, you must specify a correct IComparer<T> for those keys. For example, with string keys (which exhibit this issue), you must do the following in order to get correct results:

编辑:正如Jeppe Stig Nielsen所指出的,有些对象有一个IComparer ,它与它们的IEqualityComparer 不兼容,产生不正确的结果。当使用此类对象的键时,必须为这些键指定正确的IComparer 。例如,使用string键(显示这个问题),您必须执行以下操作才能得到正确的结果:

dictionary1.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key, StringComparer.Ordinal))

#3


13  

In addition to the mentioned SequenceEqual, which

除了前面提到的顺序相等之外

is true if two lists are of equal length and their corresponding elements compare equal according to a comparer

如果两个列表的长度相等,并且它们对应的元素按照比较器进行比较,是否正确

(which may be the default comparer, i.e. an overriden Equals())

(可能是默认比较器,即overriden Equals()))

it is worth mentioning that in .Net4 there is SetEquals on ISet objects, which

值得一提的是,在。net4中,ISet对象上有SetEquals。

ignores the order of elements and any duplicate elements.

忽略元素的顺序和任何重复的元素。

So if you want to have a list of objects, but they don't need to be in a specific order, consider that an ISet (like a HashSet) may be the right choice.

因此,如果您想要一个对象列表,但是它们不需要按特定的顺序排列,可以考虑使用ISet(比如HashSet)可能是正确的选择。

#4


8  

Take a look at the Enumerable.SequenceEqual method

看看可数名词。SequenceEqual方法

var dictionary = new Dictionary<int, string>() {{1, "a"}, {2, "b"}};
var intList = new List<int> {1, 2};
var stringList = new List<string> {"a", "b"};
var test1 = dictionary.Keys.SequenceEqual(intList);
var test2 = dictionary.Values.SequenceEqual(stringList);

#5


5  

I didn't know about Enumerable.SequenceEqual method (you learn something every day....), but I was going to suggest using an extension method; something like this:

我不知道可枚举。SequenceEqual方法(你每天都学习一些....),但我建议使用一个扩展方法;是这样的:

    public static bool IsEqual(this List<int> InternalList, List<int> ExternalList)
    {
        if (InternalList.Count != ExternalList.Count)
        {
            return false;
        }
        else
        {
            for (int i = 0; i < InternalList.Count; i++)
            {
                if (InternalList[i] != ExternalList[i])
                    return false;
            }
        }

        return true;

    }

Interestingly enough, after taking 2 seconds to read about SequenceEqual, it looks like Microsoft has built the function I described for you.

有趣的是,在花了2秒钟阅读了SequenceEqual之后,看起来微软已经构建了我为您描述的功能。

#6


5  

.NET Lacks any powerful tools for comparing collections. I've developed a simple solution you can find at the link below:

. net缺乏任何比较集合的强大工具。我开发了一个简单的解决方案,你可以在下面的链接中找到:

http://robertbouillon.com/2010/04/29/comparing-collections-in-net/

http://robertbouillon.com/2010/04/29/comparing-collections-in-net/

This will perform an equality comparison regardless of order:

这将执行平等比较,不管顺序:

var list1 = new[] { "Bill", "Bob", "Sally" };
var list2 = new[] { "Bob", "Bill", "Sally" };
bool isequal = list1.Compare(list2).IsSame;

This will check to see if items were added / removed:

这将检查项目是否被添加/删除:

var list1 = new[] { "Billy", "Bob" };
var list2 = new[] { "Bob", "Sally" };
var diff = list1.Compare(list2);
var onlyinlist1 = diff.Removed; //Billy
var onlyinlist2 = diff.Added;   //Sally
var inbothlists = diff.Equal;   //Bob

This will see what items in the dictionary changed:

这将会看到字典里的条目发生了什么变化:

var original = new Dictionary<int, string>() { { 1, "a" }, { 2, "b" } };
var changed = new Dictionary<int, string>() { { 1, "aaa" }, { 2, "b" } };
var diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);
foreach (var item in diff.Different)
  Console.Write("{0} changed to {1}", item.Key.Value, item.Value.Value);
//Will output: a changed to aaa

#7


3  

This is not directly answering your questions, but both the MS' TestTools and NUnit provide

这并不是直接回答您的问题,而是MS的TestTools和NUnit提供的

 CollectionAssert.AreEquivalent

which does pretty much what you want.

这基本上就是你想要的。

#8


1  

To compare collections you can also use LINQ. Enumerable.Intersect returns all pairs that are equal. You can comparse two dictionaries like this:

要比较集合,还可以使用LINQ。可列举的。Intersect返回所有相等的对。你可以像这样比较两本字典:

(dict1.Count == dict2.Count) && dict1.Intersect(dict2).Count() == dict1.Count

The first comparison is needed because dict2 can contain all the keys from dict1 and more.

需要进行第一次比较,因为dict2可以包含来自dict1及更多版本的所有键。

You can also use think of variations using Enumerable.Except and Enumerable.Union that lead to similar results. But can be used to determine the exact differences between sets.

您还可以使用枚举的变体来考虑变量。除了和枚举。这导致了类似的结果。但是可以用来确定集合之间的确切区别。

#9


1  

How about this example:

这个例子:

 static void Main()
{
    // Create a dictionary and add several elements to it.
    var dict = new Dictionary<string, int>();
    dict.Add("cat", 2);
    dict.Add("dog", 3);
    dict.Add("x", 4);

    // Create another dictionary.
    var dict2 = new Dictionary<string, int>();
    dict2.Add("cat", 2);
    dict2.Add("dog", 3);
    dict2.Add("x", 4);

    // Test for equality.
    bool equal = false;
    if (dict.Count == dict2.Count) // Require equal count.
    {
        equal = true;
        foreach (var pair in dict)
        {
            int value;
            if (dict2.TryGetValue(pair.Key, out value))
            {
                // Require value be equal.
                if (value != pair.Value)
                {
                    equal = false;
                    break;
                }
            }
            else
            {
                // Require key be present.
                equal = false;
                break;
            }
        }
    }
    Console.WriteLine(equal);
}

Courtesy : https://www.dotnetperls.com/dictionary-equals

礼貌:https://www.dotnetperls.com/dictionary-equals

#10


0  

No. The collection framework doesn't have any concept of equality. If you think about it there is no way of comparing collections which isn't subjective. For instance comparing your IList to your Dictionary, would they be equal if all the keys were in the IList, all the values were in the IList or if both were in the IList? There is no obvious way of comparing these two collections without knowledge of what they are to be used for so a general purpose equals method makes no sense.

不。集合框架没有任何平等的概念。如果你仔细想想,就会发现没有一种方法可以比较非主观的集合。比如比较你的《伊利亚特》和你的字典,如果所有的键都在《伊利亚特》中,所有的值都在《伊利亚特》中,或者两者都在《伊利亚特》中,它们会相等吗?没有明显的方法来比较这两个集合而不知道它们是用来做什么的,所以一个通用的目的等于方法是没有意义的。

#11


0  

No, because the framework doesn't know how to compare the contents of your lists.

不,因为框架不知道如何比较列表的内容。

Have a look at this:

看看这个:

http://blogs.msdn.com/abhinaba/archive/2005/10/11/479537.aspx

http://blogs.msdn.com/abhinaba/archive/2005/10/11/479537.aspx

#12


0  

public bool CompareStringLists(List<string> list1, List<string> list2)
{
    if (list1.Count != list2.Count) return false;

    foreach(string item in list1)
    {
        if (!list2.Contains(item)) return false;
    }

    return true;
}

#13


0  

There wasn't, isn't and might not be, at least I would believe so. The reason behind is collection equality is probably an user defined behavior.

没有,没有,也可能没有,至少我相信是这样。原因是集合相等性可能是用户定义的行为。

Elements in collections are not supposed to be in a particular order though they do have an ordering naturally, it's not what the comparing algorithms should rely on. Say you have two collections of:

集合中的元素不应该按照特定的顺序排列,尽管它们具有自然的顺序,但这不是比较算法应该依赖的。假设你有两个集合:

{1, 2, 3, 4}
{4, 3, 2, 1}

Are they equal or not? You must know but I don't know what's your point of view.

它们是否相等?你必须知道,但我不知道你的观点是什么。

Collections are conceptually unordered by default, until the algorithms provide the sorting rules. The same thing SQL server will bring to your attention is when you trying to do pagination, it requires you to provide sorting rules:

默认情况下,集合在概念上是无序的,直到算法提供排序规则为止。同样的SQL server也会引起你的注意,当你试图进行分页时,它需要你提供排序规则:

https://docs.microsoft.com/en-US/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-2017

https://docs.microsoft.com/en - us/sql/t sql/queries/select秩序——通过条款-处理- sql?view=sql -服务器- 2017

Yet another two collections:

另一个两个集合:

{1, 2, 3, 4}
{1, 1, 1, 2, 2, 3, 4}

Again, are they equal or not? You tell me ..

同样,它们是否相等?你告诉我. .

Element repeatability of a collection plays its role in different scenarios and some collections like Dictionary<TKey, TValue> don't even allow repeated elements.

集合的元素可重复性在不同的场景中扮演着重要的角色,有些集合如Dictionary 甚至不允许重复元素。 ,>

I believe these kinds of equality are application defined and the framework therefore did not provide all of the possible implementations.

我认为这些平等是定义好的应用程序,因此框架没有提供所有可能的实现。

Well, in general cases Enumerable.SequenceEqual is good enough but it returns false in the following case:

一般情况下是可列举的。SequenceEqual足够好,但在以下情况下返回false:

var a = new Dictionary<String, int> { { "2", 2 }, { "1", 1 }, };
var b = new Dictionary<String, int> { { "1", 1 }, { "2", 2 }, };
Debug.Print("{0}", a.SequenceEqual(b)); // false

I read some answers to questions like this(you may google for them) and what I would use, in general:

我读了一些这样的问题的答案(你可以用谷歌来回答),我一般会用些什么:

public static class CollectionExtensions {
    public static bool Represents<T>(this IEnumerable<T> first, IEnumerable<T> second) {
        if(object.ReferenceEquals(first, second)) {
            return true;
        }

        if(first is IOrderedEnumerable<T> && second is IOrderedEnumerable<T>) {
            return Enumerable.SequenceEqual(first, second);
        }

        if(first is ICollection<T> && second is ICollection<T>) {
            if(first.Count()!=second.Count()) {
                return false;
            }
        }

        first=first.OrderBy(x => x.GetHashCode());
        second=second.OrderBy(x => x.GetHashCode());
        return CollectionExtensions.Represents(first, second);
    }
}

That means one collection represents the other in their elements including repeated times without taking the original ordering into account. Some notes of the implementation:

这意味着一个集合在其元素中表示另一个集合,包括重复的次数,而没有考虑原始排序。执行情况的一些说明:

  • GetHashCode() is just for the ordering not for equality; I think it's enough in this case

    GetHashCode()只是用于排序而不是用于平等;我认为在这种情况下已经足够了

  • Count() will not really enumerates the collection and directly fall into the property implementation of ICollection<T>.Count

    Count()不会真正枚举集合,直接属于ICollection .Count .Count的属性实现

  • If the references are equal, it's just Boris

    如果引用是相等的,那就是Boris