Comparing two List for equality

后端 未结 9 1378
时光说笑
时光说笑 2020-12-01 11:30

Other than stepping through the elements one by one, how do I compare two lists of strings for equality (in .NET 3.0):

This fails:

// Expected re         


        
相关标签:
9条回答
  • 2020-12-01 12:22

    Using Linq and writing the code as an extension method :

    public static bool EqualsOtherList<T>(this List<T> thisList, List<T> theOtherList)
    {
      if (thisList == null || theOtherList == null || 
          thisList.Count != theOtherList.Count) return false;
      return !thisList.Where((t, i) => !t.Equals(theOtherList[i])).Any();
    }
    
    0 讨论(0)
  • 2020-12-01 12:27

    I noticed no one actually told you why your original code didn't work. This is because the == operator in general tests reference equality (i.e. if the two instances are pointing to the same object in memory) unless the operator has been overloaded. List<T> does not define an == operator so the base reference equals implementation is used.

    As other posters have demonstrated, you will generally have to step through elements to test "collection equality." Of course, you should use the optimization suggested by user DreamWalker which first tests the Count of the collections before stepping through them.

    0 讨论(0)
  • 2020-12-01 12:28

    Many test frameworks offer a CollectionAssert class:

    CollectionAssert.AreEqual(expected, actual);
    

    E.g MS Test

    0 讨论(0)
提交回复
热议问题