2021-04-07 01:27:35 +01:00
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
2021-06-23 04:25:23 +01:00
|
|
|
using System.Threading.Tasks;
|
2021-04-07 01:27:35 +01:00
|
|
|
|
|
|
|
|
public static class CollectionExtensions
|
|
|
|
|
{
|
|
|
|
|
// https://stackoverflow.com/a/3188835
|
|
|
|
|
public static T MaxBy<T, U>(this IEnumerable<T> items, Func<T, U> selector)
|
|
|
|
|
{
|
|
|
|
|
if (!items.Any())
|
|
|
|
|
{
|
|
|
|
|
throw new InvalidOperationException("Empty input sequence");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var comparer = Comparer<U>.Default;
|
|
|
|
|
T maxItem = items.First();
|
|
|
|
|
U maxValue = selector(maxItem);
|
|
|
|
|
|
|
|
|
|
foreach (T item in items.Skip(1))
|
|
|
|
|
{
|
|
|
|
|
// Get the value of the item and compare it to the current max.
|
|
|
|
|
U value = selector(item);
|
|
|
|
|
if (comparer.Compare(value, maxValue) > 0)
|
|
|
|
|
{
|
|
|
|
|
maxValue = value;
|
|
|
|
|
maxItem = item;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return maxItem;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static T MinBy<T, U>(this IEnumerable<T> items, Func<T, U> selector)
|
|
|
|
|
{
|
|
|
|
|
if (!items.Any())
|
|
|
|
|
{
|
|
|
|
|
throw new InvalidOperationException("Empty input sequence");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var comparer = Comparer<U>.Default;
|
|
|
|
|
T maxItem = items.First();
|
|
|
|
|
U maxValue = selector(maxItem);
|
|
|
|
|
|
|
|
|
|
foreach (T item in items.Skip(1))
|
|
|
|
|
{
|
|
|
|
|
// Get the value of the item and compare it to the current max.
|
|
|
|
|
U value = selector(item);
|
|
|
|
|
if (comparer.Compare(value, maxValue) < 0)
|
|
|
|
|
{
|
|
|
|
|
maxValue = value;
|
|
|
|
|
maxItem = item;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return maxItem;
|
|
|
|
|
}
|
2021-06-23 04:25:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static class AsyncAwaitExtensions
|
|
|
|
|
{
|
|
|
|
|
public static async void WrapAwait(this Task task)
|
|
|
|
|
{
|
|
|
|
|
await task;
|
|
|
|
|
}
|
2026-06-13 07:36:08 +01:00
|
|
|
}
|