AndreyBogach / morelinq

Automatically exported from code.google.com/p/morelinq
Apache License 2.0
0 stars 0 forks source link

Implement SingleOrNew #12

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
Implement SingleOrNew as per 
http://stackoverflow.com/questions/561762/what-about-a-singleornew-method-
instead-of-singleordefault-in-linq/561787#561787

Original issue reported on code.google.com by jonathan.skeet on 18 Feb 2009 at 4:19

GoogleCodeExporter commented 8 years ago
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();
}

Original comment by azizatif on 18 Feb 2009 at 5:04

GoogleCodeExporter commented 8 years ago
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...

Original comment by CAmmerman@gmail.com on 19 Feb 2009 at 3:54

GoogleCodeExporter commented 8 years ago
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.

Original comment by jonathan.skeet on 20 Feb 2009 at 9:38

GoogleCodeExporter commented 8 years ago
Implemented SingleOrFallback, but need an overload taking a predicate (just 
like 
SingleOrDefault). Will do FallbackIfEmpty too.

Original comment by jonathan.skeet on 20 Feb 2009 at 10:28

GoogleCodeExporter commented 8 years ago
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 :)

Original comment by tormod.s...@gmail.com on 16 Jun 2012 at 12:05

GoogleCodeExporter commented 8 years ago
This issue has been migrated to:
https://github.com/MoreLINQ/morelinq/issues/12
The conversation continues there.
DO NOT post any further comments to the issue tracker on Google Code as it is 
shutting down.
You can also just subscribe to the issue on GitHub to receive notifications of 
any further development.

Original comment by azizatif on 21 Aug 2015 at 6:54