Sounds like it could be done, yes. Can't say I remember having been in a situation where I'd use it myself, but it's easy enough to implement. Something like this:
public static T SingleOrNew<T>(this IEnumerable<T> source) where T : new()
{
if (source == null)
{
throw new ArgumentNullException("source");
}
using (IEnumerator<T> iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
return new T();
}
T first = iterator.Current;
if (iterator.MoveNext())
{
throw new InvalidOperationException();
}
return first;
}
}
I'll add it to the list of operators to include in MoreLinq...
Another, more general approach would be to provide a delegate which would only be evaluated if necessary (I need a better name here, admittedly):
public static T SingleOrSpecifiedDefault<T>(this IEnumerable<T> source,
Func<T> defaultSelector)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (defaultSelector == null)
{
throw new ArgumentNullException("defaultSelector");
}
using (IEnumerator<T> iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
return defaultSelector();
}
T first = iterator.Current;
if (iterator.MoveNext())
{
throw new InvalidOperationException();
}
return first;
}
}