Compares a collection of objects of a given type with another collection of objects with the same given type to see if they are the same. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Compares a collection of objects of a given type with another collection of objects with the same given type to see if they are the same.

Demo Code


using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System;/*from ww  w  .  ja v a2  s .  co m*/

public class Main{
        /// <summary>
        /// Compares a collection of objects of a given type with another collection of objects with the same given type to see if they are the same.
        /// </summary>
        /// <param name="collection">
        /// The initial collection of items.
        /// </param>
        /// <param name="collectionB">
        /// The collection to compare with.
        /// </param>
        /// <typeparam name="T">
        /// The type of objects in the collections.
        /// </typeparam>
        /// <returns>
        /// Returns true if contains all the items in the collection; else false.
        /// </returns>
        public static bool Matches<T>(this IEnumerable<T> collection, IEnumerable<T> collectionB)
        {
            if (collection == null && collectionB == null)
            {
                return true;
            }

            if (collection == null)
            {
                return false;
            }

            if (collectionB == null)
            {
                return false;
            }

            var list1 = collection as IList<T> ?? collection.ToList();
            var list2 = collectionB as IList<T> ?? collectionB.ToList();

            return list1.ToList().Count == list2.ToList().Count
                   && list1.OrderBy(t => t).SequenceEqual(list2.OrderBy(t => t));
        }
}

Related Tutorials