From 482424a714c129e8ecd9cc8f780dededa0414816 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Mon, 12 Feb 2018 14:32:36 -0500 Subject: [PATCH] Adding extension method for finding distinct items in a sequence based on a callback --- .../Extensions/EnumerableExtensions.cs | 20 +++++++++++ ICD.Common.Utils/FuncComparer.cs | 33 +++++++++++++++++++ .../ICD.Common.Utils_SimplSharp.csproj | 1 + 3 files changed, 54 insertions(+) create mode 100644 ICD.Common.Utils/FuncComparer.cs diff --git a/ICD.Common.Utils/Extensions/EnumerableExtensions.cs b/ICD.Common.Utils/Extensions/EnumerableExtensions.cs index d28fe0a..d8c0ae1 100644 --- a/ICD.Common.Utils/Extensions/EnumerableExtensions.cs +++ b/ICD.Common.Utils/Extensions/EnumerableExtensions.cs @@ -643,6 +643,7 @@ namespace ICD.Common.Utils.Extensions /// /// /// + [PublicAPI] public static Dictionary ToDictionary(this IEnumerable> extends) { if (extends == null) @@ -651,6 +652,25 @@ namespace ICD.Common.Utils.Extensions return extends.ToDictionary(x => x.Key, x => x.Value); } + /// + /// Shim to + /// + /// + /// + /// + /// + [PublicAPI] + public static IEnumerable Distinct(this IEnumerable extends, Func comparer) + { + if (extends == null) + throw new ArgumentNullException("extends"); + + if (comparer == null) + throw new ArgumentNullException("comparer"); + + return extends.Distinct(new FuncComparer(comparer)); + } + /// /// Returns other if the sequence is empty. /// Returns other if the sequence is non-empty and there are two different elements. diff --git a/ICD.Common.Utils/FuncComparer.cs b/ICD.Common.Utils/FuncComparer.cs new file mode 100644 index 0000000..c9bb76a --- /dev/null +++ b/ICD.Common.Utils/FuncComparer.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; + +namespace ICD.Common.Utils +{ + /// + /// Simple comparer for comparing items using a callback. + /// + /// + public sealed class FuncComparer : IEqualityComparer + { + private readonly Func m_Comparer; + + /// + /// Constructor. + /// + /// + public FuncComparer(Func comparer) + { + m_Comparer = comparer; + } + + public bool Equals(T x, T y) + { + return m_Comparer(x, y); + } + + public int GetHashCode(T obj) + { + return obj.GetHashCode(); + } + } +} diff --git a/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj b/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj index e6a5e80..966b40e 100644 --- a/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj +++ b/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj @@ -87,6 +87,7 @@ +