Compares two dictionary for equality. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IDictionary

Description

Compares two dictionary for equality.

Demo Code

//   Copyright (c) Slash Games. All rights reserved.
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections;

public class Main{

        /// <summary>
        ///   Compares two dictionary for equality.
        /// </summary>
        /// <typeparam name="TKey">Type of dictionary keys.</typeparam>
        /// <typeparam name="TValue">Type of dictionary values.</typeparam>
        /// <param name="first">First dictionary.</param>
        /// <param name="second">Second dictionary.</param>
        /// <returns>True if the two dictionaries are equal; otherwise, false.</returns>
        public static bool DictionaryEqual<TKey, TValue>(
            IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
        {//from  w  w w  . j  a  v a 2  s .c  o m
            if (first == second)
            {
                return true;
            }
            if ((first == null) || (second == null))
            {
                return false;
            }
            if (first.Count != second.Count)
            {
                return false;
            }

            EqualityComparer<TValue> comparer = EqualityComparer<TValue>.Default;

            foreach (KeyValuePair<TKey, TValue> kvp in first)
            {
                TValue secondValue;
                if (!second.TryGetValue(kvp.Key, out secondValue))
                {
                    return false;
                }

                if (kvp.Value is IEnumerable && secondValue is IEnumerable)
                {
                    IEnumerable enumerable1 = (IEnumerable)kvp.Value;
                    IEnumerable enumerable2 = (IEnumerable)secondValue;
                    if (!SequenceEqual(enumerable1.Cast<object>(), enumerable2.Cast<object>()))
                    {
                        return false;
                    }
                }
                else
                {
                    if (!comparer.Equals(kvp.Value, secondValue))
                    {
                        return false;
                    }
                }
            }
            return true;
        }
}

Related Tutorials