2
var person = People.SingleOrDefault(p => p.Name == parameter);
SelectedPerson = person ?? DefaultPerson

Could this be written in one statement? Measing can I provide the default element that SingleOrDefault returns?

I am looking for someting like this (the second argument is the default element I provide).

var person = People.SingleOrDefault(p => p.Name == parameter, DefaultPerson);

The solution should also work for value types (ints, doubles, enums, structs, ...).

2
  • 3
    what about SelectedPerson = People.SingleOrDefault(p => p.Name == parameter)??DefaultPerson? it should work. Commented Apr 26, 2013 at 18:02
  • How will you distinguish between a "valid" 0 or a "default" 0 for ints? Commented Apr 26, 2013 at 18:12

4 Answers 4

7

You can use DefaultIfEmpty():

var person = People.Where(p => p.Name == parameter).DefaultIfEmpty(DefaultPerson).Single();
Sign up to request clarification or add additional context in comments.

2 Comments

DefaultIfEmpty still returns IEnumerable so another First() is necessary. But yes, that's what I was looking for! Thx
@WolfgangZiegler: another Single() would be necessary to provide the same behavior.
4

You can define an extension:

public static T SingleOrDefault<T>
    (this IEnumerable<T> list, T defaultValue) 
    where T : class
{
    return list.SingleOrDefault() ?? defaultValue;
}

and then call it with:

var person = People.SingleOrDefault(p => p.Name == parameter, DefaultPerson);

Comments

2

It's a little obvious, but would this work for you?

var person = People.SingleOrDefault(p => p.Name == parameter) ?? DefaultPerson;

1 Comment

I am looking for a more generic solution, that would also work with value types (int, double, structs, ...). Sorry for the bad example ...
-1

You can create an extension method, which give you an instance if nothing will be found:

public static class PersonExtensionMethod
{
    public static T SingleOrInstance<T>(this IEnumerable<T> source, Func<T, bool> precate)
    {
        var person = source.SingleOrDefault(precate);

        if (person == null)
            return (T)Activator.CreateInstance(typeof(T));

        return person;
    }
}

and call it like this:

 List<Person> persons = new List<Person> { new Person(), new Person(), new Person() };

 var foundPerson = persons.SingleOrInstance<Person>(p => p.Name == "bla");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.