Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace CollectionEquality
- {
- public static class CollectionExtensions
- {
- public static bool EquivalentWith<T>(this IEnumerable<T> source, IEnumerable<T> other)
- {
- return EquivalentWith(source, other, EqualityComparer<T>.Default);
- }
- public static bool EquivalentWith<T>(this IEnumerable<T> source, IEnumerable<T> other, IEqualityComparer<T> comparer)
- {
- if (source == null) throw new ArgumentNullException("source");
- if (other == null) throw new ArgumentNullException("other");
- if (comparer == null) throw new ArgumentNullException("comparer");
- if (ReferenceEquals(source, other))
- {
- return true;
- }
- if (CollectionsButNotSameCount(source, other))
- {
- return false;
- }
- int sourceNullCount;
- var sourceDict = GetElementCounts(source, comparer, out sourceNullCount);
- int otherNullCount;
- var otherDict = GetElementCounts(other, comparer, out otherNullCount);
- if (otherNullCount != sourceNullCount || sourceDict.Count != otherDict.Count)
- {
- return false;
- }
- foreach (var s in sourceDict)
- {
- int otherCount;
- if (!otherDict.TryGetValue(s.Key, out otherCount) || s.Value != otherCount)
- {
- return false;
- }
- }
- return true;
- }
- private static bool CollectionsButNotSameCount<T>(IEnumerable<T> source, IEnumerable<T> other)
- {
- var sourceColl = source as ICollection<T>;
- var otherColl = other as ICollection<T>;
- return sourceColl != null && otherColl != null && sourceColl.Count != otherColl.Count;
- }
- private static Dictionary<T, int> GetElementCounts<T>(IEnumerable<T> source, IEqualityComparer<T> comparer, out int nullCount)
- {
- var asCollection = source as ICollection<T>;
- var dictionary = new Dictionary<T, int>(asCollection == null ? 0 : asCollection.Count, comparer);
- nullCount = 0;
- foreach (var key in source)
- {
- if (key == null)
- {
- ++nullCount;
- }
- else
- {
- int num;
- dictionary.TryGetValue(key, out num);
- ++num;
- dictionary[key] = num;
- }
- }
- return dictionary;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement