简体   繁体   English

我如何比较两个通用集合?

[英]How can I compare two generic collections?

How can I compare two generic collections? 我如何比较两个通用集合? Here's my attempt with two string arrays, but it doesn't return true. 这是我尝试使用两个字符串数组,但它不会返回true。

namespace genericCollections
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] xx = new string[] { "gfdg", "gfgfd", "fgfgfd" };
            string[] yy = new string[] { "gfdg", "gfgfd", "fgfgfd" };
            Console.WriteLine(ComparerCollection(xx, yy).ToString());
            Console.ReadKey();
        }

        static bool ComparerCollection<T>(ICollection<T> x, ICollection<T> y)
        {
            return x.Equals(y);
        }
    }
}

调用Enumerable.SequenceEqual

bool arraysAreEqual = xx.SequenceEqual(yy);

From the MSDN documenation: 从MSDN文档:

The default implementation of Equals supports reference equality only, but derived classes can override this method to support value equality. Equals的默认实现仅支持引用相等,但派生类可以重写此方法以支持值相等。

In your case xx and yy are two different instances of string[] so they are never equal. 在你的情况下,xx和yy是string []的两个不同实例,所以它们永远不会相等。 You'd have to override the .Equal() method of the string[] 你必须覆盖字符串[]的.Equal()方法

But you can simply solve it by looping through the entire collection 但你可以通过循环整个集合来解决它

static bool CompareCollection<T>(ICollection<T> x, ICollection<T> y)
{
       if (x.Length != y.Length)
            return false;

       for(int i = 0; i < x.Length,i++)
       {
           if (x[i] != y[i])
               return false;
       }

       return true;
}

您可以使用LINQ获取xx但不在xy中的元素:

 var newInXY = xx.Except(xy);

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

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