Skip to content

TrySingle : xs → Zero | (x, One) | Many #540

@jimmcslim

Description

@jimmcslim

I'm wondering whether the community would think that TrySingle would be a useful addition to MoreLINQ.

public static Cardinality TrySingle<T>(this IEnumerable<T> values, out T result)
public enum Cardinality { Zero, One, Many }

Where the behaviour of TrySingle is to attempt to return the first, single element from the enumerable. If the enumerable has a single element, out result is populated with the item, and Cardinality.One is returned. However, if there are zero items in the enumerable then the method returns Cardinality.Zero; if there are multiple items in the enumerable then the method returns Cardinality.Many. In both of these cases the out result is null.

A consumer of this method can then distinctly handle the Zero or Many cases in whichever special way is required.

I'm happy to submit a PR if this is worthwhile.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions