8000 Split collection in two by predicate · Issue #264 · morelinq/MoreLINQ · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Split collection in two by predicate #264
Closed
@Alexander882

Description

@Alexander882

Sometimes, you need to handle the elements of a collection differently, based on whether they satisfy a predicate or not.
To do this, you could just perform a Where operation on the source collection to get the elements that satisfy the predicate, and another Where to get the elements that don't satisfy the predicate.
This, however, requires multiple enumerations of the source collection, and writing the predicate twice, with and without a not operator.
I'd propose a new operator SplitBy that does this.

public static PredicatedCollections<T> SplitBy<T>(this IEnumerable<T> source, Predicate<T> predicate)

Returning a strongly-typed object with the two collections:

public class PredicatedCollections<T>
{
    public IEnumerable<T> SatisfiedCollection { get; }
    public IEnumerable<T> UnsatisfiedCollection { get; }
}

The result could be calculated eagerly (returning ILists) or lazily.

Example

var numbers = new [] { -10, 5, -1, 3 };
var result = numbers.SplitBy(n => n >= 0);
var positives = result.SatisfiedCollection; // [5, 3]
var negatives = result.UnsatisfiedCollection; // [-10, -1]

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0