Skip to content

Instantly share code, notes, and snippets.

@AmirOfir
Created July 30, 2018 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmirOfir/4cc199be42d5f3e829c394cb473812e5 to your computer and use it in GitHub Desktop.
Save AmirOfir/4cc199be42d5f3e829c394cb473812e5 to your computer and use it in GitHub Desktop.
Group IEnumerable<T> by key, and get the first item from each group using a predicate
public static IEnumerable<T> FirstGroupItems<T, TKey>(this IEnumerable<T> list, Func<T, TKey> keySelector, Func<IGrouping<TKey, T>, T> firstPredicate = null) where T : class
{
return list.GroupBy(keySelector).Select(a => firstPredicate == null ? a.First() : firstPredicate(a) ?? a.First());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment