Return true if the given enumerables have the same contents - CSharp System.Collections

CSharp examples for System.Collections:IEnumerable

Description

Return true if the given enumerables have the same contents

Demo Code

// This software is licensed under the LGPL, version 2.1 or later
using System.Linq;
using System.Collections;
using System.Text;
using System.Collections.Generic;
using System;// w  w w.ja va 2s  . c  om

public class Main{
    /// ------------------------------------------------------------------------------------
      /// <summary>
      /// Return true if the given enumerables have the same contents
      /// </summary>
      /// ------------------------------------------------------------------------------------
      public static bool AreEqual(IEnumerable e1, IEnumerable e2)
      {
         // both empty is equivalent
         if (e1 == null && e2 == null)
            return true;

         if (e1 != null && e2 != null)
         {
            IEnumerator e1Enum = e1.GetEnumerator();
            IEnumerator e2Enum = e2.GetEnumerator();
            // Be very careful about changing this. Remember MoveNext() changes the state.
            // You can't test it twice and have it mean the same thing.
            while (e1Enum.MoveNext())
            {
               if (e2Enum.MoveNext())
               {
                  if (!e1Enum.Current.Equals(e2Enum.Current))
                     return false; // items at current position are not equal
               }
               else
               {
                  return false; // collection 2 is shorter
               }
            }
            // Come to the end of e1Enum and all elements so far matched.
            return !e2Enum.MoveNext(); // if there are more in e2 they are not equal
         }
         return false; // one (only) is null
      }
}

Related Tutorials