Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Created December 10, 2021 11:16
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 gsscoder/72aa44ab0b4b222888328e4bda57d9ff to your computer and use it in GitHub Desktop.
Save gsscoder/72aa44ab0b4b222888328e4bda57d9ff to your computer and use it in GitHub Desktop.
C# extension method to partition sequences by a value
using System;
using System.Collections.Generic;
using System.Linq;
using SharpX.Extensions;
static class EnumerableExtensions
{
public static IEnumerable<IEnumerable<T>> Partition<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector)
{
var result = new List<IEnumerable<T>>();
var ordered = source.OrderBy(selector);
var partition = new List<T>();
for (var i = 0; i < ordered.Count(); i++) {
var current = ordered.ElementAt(i);
var currentValue = selector(current);
partition.Add(current);
if (ordered.ElementAtOrNothing(i + 1).MatchJust(out var next)) {
var nextValue = selector(next);
if (currentValue.Equals(nextValue)) {
continue;
}
else {
result.Add(new List<T>(partition));
partition.Clear();
}
}
else {
result.Add(partition);
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment