Skip to content

Instantly share code, notes, and snippets.

@JohanLarsson
Last active December 18, 2015 03:49
Show Gist options
  • Save JohanLarsson/5720898 to your computer and use it in GitHub Desktop.
Save JohanLarsson/5720898 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using NUnit.Framework;
class LinqExtTests
{
[TestCase(0, 0, 0, 0)]
[TestCase(1, 0, 0, 0)]
[TestCase(0, 1, 0, 1)]
[TestCase(0, 0, 1, 2)]
public void MaxByTest(int first, int second, int third, int expectedIndex)
{
var list = new List<Fake> { new Fake(first), new Fake(second), new Fake(third) };
var maxBy = list.MaxBy(x => x.Value);
Assert.AreEqual(list[expectedIndex], maxBy);
}
[TestCase(0, 0, 0, 0)]
[TestCase(-1, 0, 0, 0)]
[TestCase(0, -1, 0, 1)]
[TestCase(0, 0, -1, 2)]
public void MinByTest(int first, int second, int third, int expectedIndex)
{
var list = new List<Fake> { new Fake(first), new Fake(second), new Fake(third) };
var maxBy = list.MïnBy(x => x.Value);
Assert.AreEqual(list[expectedIndex], maxBy);
}
private class Fake
{
public Fake(int value)
{
Value = value;
}
public int Value { get; private set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
public static class LinqEx
{
public static T MaxBy<T, U>(this IEnumerable<T> seq, Func<T, U> test, IComparer<U> cmp)
{
using (var en = seq.GetEnumerator())
{
if (!en.MoveNext())
throw new InvalidOperationException("Sequence has no elements");
T max = en.Current;
U maxValue = test(max);
while (en.MoveNext())
{
T current = en.Current;
U currentValue = test(current);
if (cmp.Compare(currentValue, maxValue) > 0)
{
max = current;
maxValue = currentValue;
}
}
return max;
}
}
public static T MaxBy<T, U>(this IEnumerable<T> seq, Func<T, U> test) where U : IComparable
{
return seq.MaxBy(test, Comparer<U>.Default);
}
public static T MïnBy<T, U>(this IEnumerable<T> seq, Func<T, U> test, IComparer<U> cmp)
{
using (var en = seq.GetEnumerator())
{
if (!en.MoveNext())
throw new InvalidOperationException("Sequence has no elements");
T min = en.Current;
U minValue = test(min);
while (en.MoveNext())
{
T current = en.Current;
U currentValue = test(current);
if (cmp.Compare(currentValue, minValue) < 0)
{
min = current;
minValue = currentValue;
}
}
return min;
}
}
public static T MïnBy<T, U>(this IEnumerable<T> seq, Func<T, U> test) where U : IComparable
{
return seq.MïnBy(test, Comparer<U>.Default);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment