Added MinBy, MaxBy, MinByOrDefault and MaxByOrDefault methods and replaced calls of the style OrderBy[Descending]().First[OrDefault]() which is not as performant.
This commit is contained in:
@@ -131,6 +131,54 @@ namespace OpenRA
|
||||
for (;;) { yield return t; t = f(t); }
|
||||
}
|
||||
|
||||
public static T MinBy<T, U>(this IEnumerable<T> ts, Func<T, U> selector)
|
||||
{
|
||||
return ts.CompareBy(selector, 1, true);
|
||||
}
|
||||
|
||||
public static T MaxBy<T, U>(this IEnumerable<T> ts, Func<T, U> selector)
|
||||
{
|
||||
return ts.CompareBy(selector, -1, true);
|
||||
}
|
||||
|
||||
public static T MinByOrDefault<T, U>(this IEnumerable<T> ts, Func<T, U> selector)
|
||||
{
|
||||
return ts.CompareBy(selector, 1, false);
|
||||
}
|
||||
|
||||
public static T MaxByOrDefault<T, U>(this IEnumerable<T> ts, Func<T, U> selector)
|
||||
{
|
||||
return ts.CompareBy(selector, -1, false);
|
||||
}
|
||||
|
||||
static T CompareBy<T, U>(this IEnumerable<T> ts, Func<T, U> selector, int modifier, bool throws)
|
||||
{
|
||||
var comparer = Comparer<U>.Default;
|
||||
T t;
|
||||
U u;
|
||||
using (var e = ts.GetEnumerator())
|
||||
{
|
||||
if (!e.MoveNext())
|
||||
if (throws)
|
||||
throw new ArgumentException("Collection must not be empty.", "ts");
|
||||
else
|
||||
return default(T);
|
||||
t = e.Current;
|
||||
u = selector(t);
|
||||
while (e.MoveNext())
|
||||
{
|
||||
T nextT = e.Current;
|
||||
U nextU = selector(nextT);
|
||||
if (comparer.Compare(nextU, u) * modifier < 0)
|
||||
{
|
||||
t = nextT;
|
||||
u = nextU;
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
public static int NextPowerOf2(int v)
|
||||
{
|
||||
--v;
|
||||
|
||||
Reference in New Issue
Block a user