Reputation: 7804
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
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
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:
DefaultIfEmpty
to make sure that the sequence contains exactly one item (if it had one already, DefaultIfEmpty
will do nothing).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