Peter
Peter

Reputation: 7804

How to make a default(TSource)

In Linq When I call SingleOrDefault or FirstOrDefault how do I return something other than null for a particular object eg.

        List<CrazyControls> cc = CrazyControlRepository.All();
        cc.SingleOrDefault(p => p.Id == id).Render();

How do I make my CrazyControls return a default instance that implements a base Render() method?

Upvotes: 2

Views: 1503

Answers (2)

Alex Aza
Alex Aza

Reputation: 78487

You need to define this `something' that you want to return if there are no elements:

(cc.SingleOrDefault(p => p.Id == id) ?? new CrazyControls()).Render();

In other words you need to define the default value.

Upvotes: 3

Jon
Jon

Reputation: 437634

With DefaultIfEmpty(defaultValue). This will ensure that if the collection is empty, it will be populated with a default instance of the type.

So you can do:

var defaultValue = new CrazyControl(...);

List<CrazyControls> cc = CrazyControlRepository.All();
cc.Where(p => p.Id == id).DefaultIfEmpty(defaultValue).First().Render();

The query expression needed to change a bit. The new one works like this:

  1. Filter the collection according to the existing criteria. This will leave either one or no items in the filtered sequence.
  2. Use DefaultIfEmpty to make sure that the sequence contains exactly one item (if it had one already, DefaultIfEmpty will do nothing).
  3. Use First to get the single item. The reason I did not use Single instead of first is that if the predicate were different (or it changes in the future) and it accepted multiple items, Single would throw.

Upvotes: 7

Related Questions