Created
September 4, 2022 04:38
-
-
Save emoacht/21e9e6ed36ef62cff2485b89a2a5347c to your computer and use it in GitHub Desktop.
Extension method to group the elements by key in source sequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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