Created
August 1, 2011 17:42
-
-
Save bryanhunter/1118609 to your computer and use it in GitHub Desktop.
LINQ partition (specialization of GroupBy)
This file contains 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
// @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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good point... updated to be lazy.