Entension methods for finding indices in a sequence, and finding the closest item in a sequence

This commit is contained in:
Chris Cameron
2017-12-08 14:51:51 -05:00
parent 6fa4945b95
commit 1039caa016
2 changed files with 379 additions and 329 deletions

View File

@@ -123,6 +123,18 @@ namespace ICD.Common.Utils.Tests.Extensions
Assert.AreEqual(2, a.FindIndex(i => i == 3));
}
[Test]
public void FindIndicesPredicateTest()
{
IEnumerable<int> a = new[] {1, 2, 3, 4};
int[] indices = a.FindIndices(i => i % 2 == 0).ToArray();
Assert.AreEqual(2, indices.Length);
Assert.AreEqual(1, indices[0]);
Assert.AreEqual(3, indices[1]);
}
[Test]
public void SelectMultiTest()
{
@@ -144,7 +156,11 @@ namespace ICD.Common.Utils.Tests.Extensions
int[] values = {1, 2, 3};
int sum = 0;
IEnumerable<int> sequence = values.Select(v => { sum += v; return v; });
IEnumerable<int> sequence = values.Select(v =>
{
sum += v;
return v;
});
Assert.AreEqual(0, sum);
sequence.Execute();
@@ -350,6 +366,12 @@ namespace ICD.Common.Utils.Tests.Extensions
Assert.AreEqual(3, cPairs[1][1]);
}
[Test]
public void GetClosestTest()
{
Assert.AreEqual(20, new[] {10, 15, 20, 30, 35}.GetClosest(i => i - 21));
}
[Test]
public void MinByTest()
{

View File

@@ -226,6 +226,24 @@ namespace ICD.Common.Utils.Extensions
/// <param name="match"></param>
/// <returns></returns>
public static int FindIndex<T>(this IEnumerable<T> extends, Predicate<T> match)
{
if (extends == null)
throw new ArgumentNullException("extends");
if (match == null)
throw new ArgumentNullException("match");
return extends.FindIndices(match).FirstOrDefault(-1);
}
/// <summary>
/// Returns the indices that match the predicate.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <param name="match"></param>
/// <returns></returns>
public static IEnumerable<int> FindIndices<T>(this IEnumerable<T> extends, Predicate<T> match)
{
if (extends == null)
throw new ArgumentNullException("extends");
@@ -238,11 +256,9 @@ namespace ICD.Common.Utils.Extensions
foreach (T item in extends)
{
if (match(item))
return index;
yield return index;
index++;
}
return -1;
}
/// <summary>
@@ -583,6 +599,18 @@ namespace ICD.Common.Utils.Extensions
}
}
/// <summary>
/// Gets the item from the sequence with the smallest calculated delta.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <param name="getDelta"></param>
/// <returns></returns>
public static T GetClosest<T>(this IEnumerable<T> extends, Func<T, int> getDelta)
{
return extends.MinBy(n => Math.Abs(getDelta(n)));
}
/// <summary>
/// Returns the minimal element of the given sequence, based on
/// the given projection.