Implement SingleOrNew
atifaziz opened this issue · 8 comments
Implement SingleOrNew as per http://stackoverflow.com/questions/561762/what-about-a-singleornew-method-instead-of-singleordefault-in-linq/561787#561787
Originally reported on Google Code with ID 12
Reported by @jskeet on 2009-02-18 16:19:03
If we overload DefaultIfEmpty
to take a delegate (as you propose for SingleOrSpecifiedDefault
) then Single
and other similar operators can be composed on top as usual. For example:
var client = db.Clients
.Where(c => c.Name == "Some Client")
.DefaultIfEmpty(() => new Client())
.Single();
SingleOrNew
(if still needed as a helper) can then be implemented in terms of DefaultIfEmpty
plus Single
.
public static T SingleOrNew<T>(this IEnumerable<T> source)
where T : new()
{
return source.DefaultIfEmpty(() => new T()).Single();
}
Reported by @atifaziz on 2009-02-18 17:04:12
I like the idea of an override for DefaultIfEmpty
to take a delegate. I think that if we then also override SingleOrDefault
to take a similar delegate, that would cover the problem space we're looking at without making completely new methods...
Reported by @cammerman on 2009-02-19 15:54:24
I'm not sure about overloading SingleOrDefault
- too easy to confuse people, IMO. I like SingleOrFallback
which was suggested elsewhere though. Likewise we can do FallbackIfEmpty
.
Reported by @jskeet on 2009-02-20 09:38:53
Implemented SingleOrFallback
, but need an overload taking a predicate (just like SingleOrDefault
). Will do FallbackIfEmpty
too.
Reported by @jskeet on 2009-02-20 10:28:40
I realize that it will be confusing, but it would be cool (in a fluent way) to just call it SingleOr<T>(IEnumerable<T>,Func<T>)
as well as a FirstOr()
I'm not really suggesting it :)
Reported by tormod.steinsholt
on 2012-06-16 12:05:36
This is already implemented as SingleOrFallback
, but a FirstOrFallback
is missing
I think that SingleOrFallback
should not exist, and instead provide FallbackIfEmpty
, the same way that SingleOrDefault
does not provide a way to specify the default value.