[API Proposal]: Add some LINQ extension to return a single element but not throw for multiple
Background and motivation
When we are interested in whether there is exactly one element in an IEnumeable<T> (with or without a predicate), there's three possible outcomes:
- No, n=0
- Yes, n=1
- No, n>1
LINQ does currently not provide an easy way to "retrieve if n=1, default otherwise" without the need to handle exceptions: FirstOrDefault, LastOrDefault and SingleOrDefault all return default(T) for n=0, and the element for n=1. But for n> 1, the first two also return an element, and the latter throws an InvalidOperationException.
I have made the same request 6 years ago (#29398) as UniqueOrDefault, but it was closed, because Eirik Tsarpalis didn't like the name "Unique". He felt it implies the return value is a boolean, like "All" or "Any". I didn't agree; I'd name such a function "IsUnique". He didn't reply to that for a month, then just closed the issue.
Well, I don't insist on any name in particular, but I still need the functionality quite often and find myself adding a custom extension to many projects. Please re-consider adding it, under a name that you see fit.
API Proposal
namespace System.Collections.Generic;
public partial static class Enumerable
{
public static T? OnlyOrDefault<T>(this IEnumerable<T> sequence);
public static T? OnlyOrDefault<T>(this IEnumerable<T> sequence, Func<T, bool> predicate);
}
API Usage
private static bool TryGetAutoCompleteSuggestion(this IEnumerable<string> entries, string input, out string? suggestion) {
suggestion = entries.OnlyOrDefault(e => e.StartsWith(input));
return suggestion != null;
}
var selectedOption = availableOptions.OnlyOrDefault() // If there's only one option applicable, use that,
?? availableOptions.OnlyOrDefault(o => o.IsDefault) // otherwise select default option if unambiguous,
?? ShowOptionSelectDialog(availableOptions); // otherwise let the user pick one.
Alternative Designs
namespace System.Collections.Generic;
public enum Cardinality
{
Empty, // or Zero, None
Single, // or One, Only
Many // or Multiple
}
public partial static class Enumerable
{
public static bool TryGetOnly<T>(this IEnumerable<T> sequence, out T? element);
public static bool TryGetOnly<T>(this IEnumerable<T> sequence, out T? element, out Cardinality cardinality);
public static bool TryGetOnly<T>(this IEnumerable<T> sequence, Func<T, bool> predicate, out T? element);
public static bool TryGetOnly<T>(this IEnumerable<T> sequence, Func<T, bool> predicate, out T? element, out Cardinality cardinality);
}
This is fitting the "TryGet" pattern, but it wouldn't fit that well alongside [First|Last|Single](OrDefault)?
Risks
None.
Tagging subscribers to this area: @dotnet/area-system-linq See info in area-owners.md if you want to be subscribed.
Perhaps something along the lines of DistinctOrDefault would be a suitable name? There is prior art here in Enumerable.Distinct/DistinctBy.
There is prior art here in
Enumerable.Distinct/DistinctBy.
I think that's a point against the Distinct name, since it implies doing equality comparisons.
We've had a few proposals/issues on this over the years, I think the last one suggested Unique and got closed: https://github.com/dotnet/runtime/issues/29398
The suggested names have been pretty varied however and so I don't think there's a good way to link them all here.
It is a highly requested thing however and has had comments made in API review, LDM, and other meetings; not to mention at the MVP summit, Microsoft Build, and other conferences on how people wish "something" existed.
There is prior art here in
Enumerable.Distinct/DistinctBy.I think that's a point against the
Distinctname, since it implies doing equality comparisons.
But equality comparisons are inherently required to determine if the value is unique, are they not?
Edit: I think I may have misunderstood the intent of the API proposal, if it's operating based on the number of items in the collection then I agree that Distinct is not an appropriate name.
What about just adding an extra bool throwIfMultiple param to SingleOrDefault? I think the SingleOrDefault name is already ideal, it's just the behavior that needs to change.
Btw, I do like Try* methods for distinguishing between valid default values and not existing.
What about just adding an extra
bool throwIfMultipleparam toSingleOrDefault? I think theSingleOrDefaultname is already ideal, it's just the behavior that needs to change.
This is the only that makes sense trying to avoid a breaking change but, SingleOrDefault should have returned default if not single (single OR default) from the beggining. This should warrant a breaking change in my opinion.
That’s too breaking, it’s unlikely to happen
Adding an optional parameter is a breaking change?
I was responding to the following, which I took to mean suggesting we take a break in the implementation.
SingleOrDefault should have returned default if not single (single OR default) from the beggining. This should warrant a breaking change in my opinion.
Adding a new overload with a parameter is not-breaking, but the expectation (and general Framework Design Guidlines) would be that SingleOrDefault(false) has the same behavior as SingleOrDefault().
Bending a little bit your reasoning, .ConfigureAwait(true) is the default behavior, and there are some other methods (not many, I know) that put true as default, so it isn't wrong to consider SingleOrDefault() == SingleOrDefault(true).
But if that's the problem, the "dirty" solution is SingleOrDefault(bool allowMultiple = false).
I am in principle totally fine with the additional overload because it would get the thing that I need done without having to introduce the same extensions in every project.
On the other hand, it feels like a boolean overload would suffer from the typical "a boolean changes behavior" problem: unless you use a named parameter, it's not inherently obvious what the different overloads do:
list.SingleOrDefault();
list.SingleOrDefault(true);
list.SingleOrDefault(false);
Therefore, by personal API design standards, I would always try to find a distinct method name that one can learn the meaning of, rather than introducing a bool doSomethingDifferently parameter. People who have worked with LINQ a lot might have a deeply rooted belief that "Single throws for n > 1", and not even consider that SingleOrDefault(false) or SingleOrDefault(true) could change that "fundamental" known behavior.
If we are going for the overload, I'd actually also advocate to have SingleOrDefault(true) be the same, because it feels off to have false enable a behavior and true disable them. I know you can use the allowMultiple parameter name, but it feels like the exception is the added thing on top of a more lenient default behavior, not leniency that is enabled on top of a strict default behavior.
My preference in order from most to least preferred addition is:
- New extension, with a learnable, new and distinct name
SingleOrDefault(bool throwIfMultiple)⇒SingleOrDefault()⇔SingleOrDefault(true)SingleOrDefault(bool allowMultiple)⇒SingleOrDefault()⇔SingleOrDefault(false)TryGet_
The reason TryGet is ranking so low for me is
a) because in general I prefer TryGet to mean "do something, or return false if it can't be done", like for TryGetNonEnumeratedCount, the only other TryGet extension in LINQ so far, and
b) much more importantly, it would make coalesce use cases (which are my most common use case when using my current OnlyOrDefault extensions) more ugly:
var selectedOption = availableOptions.OnlyOrDefault()
?? availableOptions.OnlyOrDefault(o => o.IsDefault)
?? ShowOptionSelectDialog(availableOptions);
// vs
var selectedOption = (availableOptions.TryGet_(out var x) ? x : null)
?? (availableOptions.TryGet_(o => o.IsDefault, out var y) ? y : null)
?? ShowOptionSelectDialog(availableOptions);
We've had a few proposals/issues on this over the years, I think the last one suggested
Uniqueand got closed: #29398
This was also mine @tannergooding, as stated in the original post 😁 I had missed the opportunity to re-open back then (because I had not expected this issue to suddenly be closed that way after almost 1 year).
But now, several years later, I still find myself adding this behavior as custom extension time and time again (admittedly always under the name UniqueOrDefault). So I decided to ask for it again.
I think it's clear that, apart from the name, the general consensus is that something should exist, as you say. And I agree with @timcassell that SingleOrDefault would've been the perfect name for this behavior, but alas that is already taken.
I've been reading through this issue. I really think we need a solution for this.
To move forward, we should probably avoid adding a bool parameter to SingleOrDefault because it creates a "Boolean Trap" and looks confusing when combined with a predicate (e.g., source.SingleOrDefault(x => x.IsValid, false)). Also, a TryGet pattern breaks the clean LINQ method chaining.
A new extension method with a clear name seems like the best way to fix this deadlock. Here are a few simpler naming ideas that match .NET conventions:
AtMostOneOrDefault(): Very clear mathematically ($n \le 1$). Developers won't expect an exception if there are multiple items.StrictSingleOrDefault(): Keeps the familiarSingleprefix but tells the developer it will safely return default instead of throwing.OneOrDefault(): Short, punchy, and fits right in withFirstOrDefault.SingleOrNoneOrDefault(): Aligns perfectly with theXOrYOrDefaultnaming pattern. It explicitly tells the developer: "Return the single item, or default if none, and don't throw if multiple".UniqueOrDefault(): Clear and punchy, specifically addressing that we only care about a unique match.
Here is an example:
public static TSource? OneOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
if (predicate == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.predicate);
if (source is ICollection<TSource> collection && collection.Count == 0)
{
return default;
}
bool found = false;
TSource? result = default;
foreach (TSource element in source)
{
if (predicate(element))
{
if (found)
{
return default;
}
result = element;
found = true;
}
}
return result;
}
Why this works:
- Performance: It stops looping immediately at the second match (Early Exit), so it’s very fast and doesn't waste CPU cycles.
- Readability: It allows developers to keep using the null-coalescing operator (
??) cleanly. - Safe: It has zero breaking changes for existing code.
What does the team think about these naming compromises to finally solve this deadlock?
I wanted to post here that I could really use an OnlyOrDefault as well. I've added one to my own code, but it should be part of .NET by default.