Skip to content

Instantly share code, notes, and snippets.

@Raveler
Created February 1, 2024 08:26
Show Gist options
  • Save Raveler/8adb961b67d8b7eb6ad7a655e2df865d to your computer and use it in GitHub Desktop.
Save Raveler/8adb961b67d8b7eb6ad7a655e2df865d to your computer and use it in GitHub Desktop.
Useful extension methods for Lists in C#
using System;
using System.Collections.Generic;
using System.Linq;
public static class ListExtensions
{
public static T MaxBy<T, U>(this IEnumerable<T> data, Func<T, U> f) where U : IComparable
{
if (data.Count() == 0) throw new ArgumentException($"Cannot get the max of an empty list.");
T best = data.First();
U bestValue = f(best);
foreach (var entry in data)
{
U entryValue = f(entry);
if (entryValue.CompareTo(bestValue) > 0)
{
best = entry;
bestValue = entryValue;
}
}
return best;
}
public static int MaxByIndex<T, U>(this IEnumerable<T> data, Func<T, U> f) where U : IComparable
{
if (data.Count() == 0) throw new ArgumentException($"Cannot get the max of an empty list.");
int bestIndex = 0;
T best = data.First();
U bestValue = f(best);
int idx = 0;
foreach (var entry in data)
{
U entryValue = f(entry);
if (entryValue.CompareTo(bestValue) > 0)
{
bestIndex = idx;
best = entry;
bestValue = entryValue;
}
++idx;
}
return bestIndex;
}
public static T MinBy<T, U>(this IEnumerable<T> data, Func<T, U> f) where U : IComparable
{
if (data.Count() == 0) throw new ArgumentException($"Cannot get the min of an empty list.");
T best = data.First();
U bestValue = f(best);
foreach (var entry in data)
{
U entryValue = f(entry);
if (entryValue.CompareTo(bestValue) < 0)
{
best = entry;
bestValue = entryValue;
}
}
return best;
}
public static int MinByIndex<T, U>(this IEnumerable<T> data, Func<T, U> f) where U : IComparable
{
if (data.Count() == 0) throw new ArgumentException($"Cannot get the min of an empty list.");
int bestIndex = 0;
T best = data.First();
U bestValue = f(best);
int idx = 0;
foreach (var entry in data)
{
U entryValue = f(entry);
if (entryValue.CompareTo(bestValue) < 0)
{
bestIndex = idx;
best = entry;
bestValue = entryValue;
}
++idx;
}
return bestIndex;
}
public static T Pop<T>(this IList<T> data)
{
if (data.Count() == 0) throw new ArgumentException($"Cannot pop an element of an empty list.");
int idx = data.Count - 1;
T value = data[idx];
data.RemoveAt(idx);
return value;
}
public static string ToCommaSeparatedString<T>(this IEnumerable<T> data)
{
return string.Join(", ", data);
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> data)
{
return new HashSet<T>(data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment