Skip to content

Instantly share code, notes, and snippets.

@NDiiong
Forked from atifaziz/Partition.cs
Created August 18, 2020 03:56
Show Gist options
  • Save NDiiong/1389104fc1d571175e0b73063c04b36c to your computer and use it in GitHub Desktop.
Save NDiiong/1389104fc1d571175e0b73063c04b36c to your computer and use it in GitHub Desktop.
LINQ operator to split a sequence into two based on a condition
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
static partial class Sequence
{
/// <summary>
/// Splits the sequence into two sequences, containing the elements
/// for which the given predicate returns <c>true</c> and <c>false</c>
/// respectively.
/// </summary>
public static TResult Partition<T, TResult>(this IEnumerable<T> source,
Func<T, bool> predicate,
Func<IEnumerable<T>, IEnumerable<T>, TResult> selector)
{
if (source == null) throw new ArgumentNullException("source");
if (predicate == null) throw new ArgumentNullException("predicate");
if (selector == null) throw new ArgumentNullException("selector");
IEnumerable<T> fs = null;
IEnumerable<T> ts = null;
foreach (var g in source.GroupBy(predicate))
{
if (g.Key)
{
Debug.Assert(ts == null);
ts = g;
}
else
{
Debug.Assert(fs == null);
fs = g;
}
}
return selector(fs ?? Enumerable.Empty<T>(),
ts ?? Enumerable.Empty<T>());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment