Checks if two collections are equivalent, regardless of the order of their contents - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Checks if two collections are equivalent, regardless of the order of their contents

Demo Code

// MassSpectrometry is free software: you can redistribute it and/or modify it
using System.Linq;
using System.Collections.Generic;
using System;//from  w  w  w  .  j  a  v a  2  s .  co  m

public class Main{
        /// <summary>
        /// Checks if two collections are equivalent, regardless of the order of their contents
        /// </summary>
        public static bool ScrambledEquals<T>(this IEnumerable<T> list1, IEnumerable<T> list2)
        {
            var cnt = new Dictionary<T, int>();
            foreach (T s in list1)
            {
                if (cnt.ContainsKey(s))
                    cnt[s]++;
                else
                    cnt.Add(s, 1);
            }
            foreach (T s in list2)
            {
                if (cnt.ContainsKey(s))
                    cnt[s]--;
                else
                    return false;
            }
            return cnt.Values.All(c => c == 0);
        }
}

Related Tutorials