Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created September 4, 2022 04:38
Show Gist options
  • Save emoacht/21e9e6ed36ef62cff2485b89a2a5347c to your computer and use it in GitHub Desktop.
Save emoacht/21e9e6ed36ef62cff2485b89a2a5347c to your computer and use it in GitHub Desktop.
Extension method to group the elements by key in source sequence
public static class EnumerableExtension
{
public static IEnumerable<IGrouping<TSource, TSource>> GroupBy<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> keyFinder)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
if (keyFinder is null)
throw new ArgumentNullException(nameof(keyFinder));
TSource key = default;
return source
.Select(x =>
{
if (x is null)
return (isValid: false, default);
if (keyFinder.Invoke(x))
key = x;
return (isValid: (key is not null), value: x);
})
.Where(x => x.isValid)
.GroupBy(_ => key, x => x.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment