From 85f6486238962859455a38a27ffc7a0e1fe5d051 Mon Sep 17 00:00:00 2001 From: David Hall Date: Wed, 17 Jan 2018 12:27:24 -0700 Subject: [PATCH] Added EnumerableEqualityComparer to provide equality comparisons and full hashes of lists. --- Core/Collections/EnumerableEqualityComparer.cs | 51 ++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Core/Collections/EnumerableEqualityComparer.cs diff --git a/Core/Collections/EnumerableEqualityComparer.cs b/Core/Collections/EnumerableEqualityComparer.cs new file mode 100644 index 00000000..1d49b156 --- /dev/null +++ b/Core/Collections/EnumerableEqualityComparer.cs @@ -0,0 +1,51 @@ +using System.Collections.Generic; + +namespace Vanara.Collections +{ + /// + /// Checks the linear equality of two enumerated lists. For lists to be equal, they must have the same number of elements and each index must hold the same value in + /// each list. + /// + /// The element type in the list. + public sealed class EnumerableEqualityComparer : IEqualityComparer> + { + private static readonly EqualityComparer elementComparer = EqualityComparer.Default; + + /// Determines whether the specified lists are equal. + /// The first list of type T to compare. + /// The second list of type T to compare. + /// + public bool Equals(IEnumerable first, IEnumerable second) + { + if (ReferenceEquals(first, second)) + return true; + if (first == null || second == null) + return false; + var e1 = first.GetEnumerator(); + var e2 = second.GetEnumerator(); + bool move1 = false, move2 = false; + while ((move1 = e1.MoveNext()) && (move2 = e1.MoveNext())) + { + if (!elementComparer.Equals(e1.Current, e2.Current)) + return false; + } + return move1 == move2; + } + + /// Returns a hash code for the specified object. + /// The Object for which a hash code is to be returned. + /// A hash code for the specified object. + public int GetHashCode(IEnumerable list) + { + unchecked + { + if (list == null) + return 0; + var hash = 17; + foreach (T element in list) + hash = hash * 31 + elementComparer.GetHashCode(element); + return hash; + } + } + } +} \ No newline at end of file