Adding extension method for finding distinct items in a sequence based on a callback

This commit is contained in:
Chris Cameron
2018-02-12 14:32:36 -05:00
parent b6a1ce9bd2
commit 482424a714
3 changed files with 54 additions and 0 deletions

View File

@@ -643,6 +643,7 @@ namespace ICD.Common.Utils.Extensions
/// <typeparam name="TValue"></typeparam>
/// <param name="extends"></param>
/// <returns></returns>
[PublicAPI]
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> extends)
{
if (extends == null)
@@ -651,6 +652,25 @@ namespace ICD.Common.Utils.Extensions
return extends.ToDictionary(x => x.Key, x => x.Value);
}
/// <summary>
/// Shim to
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <param name="comparer"></param>
/// <returns></returns>
[PublicAPI]
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> extends, Func<T, T, bool> comparer)
{
if (extends == null)
throw new ArgumentNullException("extends");
if (comparer == null)
throw new ArgumentNullException("comparer");
return extends.Distinct(new FuncComparer<T>(comparer));
}
/// <summary>
/// Returns other if the sequence is empty.
/// Returns other if the sequence is non-empty and there are two different elements.

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
namespace ICD.Common.Utils
{
/// <summary>
/// Simple comparer for comparing items using a callback.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class FuncComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> m_Comparer;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="comparer"></param>
public FuncComparer(Func<T, T, bool> comparer)
{
m_Comparer = comparer;
}
public bool Equals(T x, T y)
{
return m_Comparer(x, y);
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
}
}

View File

@@ -87,6 +87,7 @@
<None Include="ObfuscationSettings.cs" />
<Compile Include="Extensions\ByteExtensions.cs" />
<Compile Include="Extensions\ListExtensions.cs" />
<Compile Include="FuncComparer.cs" />
<Compile Include="ProcessorUtils.SimplSharp.cs" />
<Compile Include="ProcessorUtils.Standard.cs" />
<Compile Include="ProgramUtils.SimplSharp.cs" />