Skip to content

Instantly share code, notes, and snippets.

@bryanhunter
Created August 1, 2011 17:42
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 bryanhunter/1118609 to your computer and use it in GitHub Desktop.
Save bryanhunter/1118609 to your computer and use it in GitHub Desktop.
LINQ partition (specialization of GroupBy)
// @hammett: "Linq doesn't have a Partition operation that returns two sets? (filtered/complement).. sad!"
// GroupBy can be seen as a partition. We specialize it to have exactly two groups:
public static class PartitionExtension
{
public static Tuple<IEnumerable<T>, IEnumerable<T>> Partition<T>(this IEnumerable<T> enumeration, Func<T, bool> criteria)
{
var whole = enumeration.GroupBy(criteria);
return new Tuple<IEnumerable<T>, IEnumerable<T>>(
whole.Where(x => x.Key).SelectMany(x => x),
whole.Where(x => !x.Key).SelectMany(x => x));
}
}
// Usage
var numbers = Enumerable.Range(1, 100);
// Partition into "even" numbers and "odd" numbers
Tuple<IEnumerable<int>, IEnumerable<int>> results = numbers.Partition((x) => x % 2 == 0);
var evens = results.Item1;
var odds = results.Item2;
@phatboyg
Copy link

phatboyg commented Aug 1, 2011

No way to do this lazy without the ToDictionary()?

@bryanhunter
Copy link
Author

Good point... updated to be lazy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment