Reputation: 10824
As you know there's an extension method called DefaultIfEmpty, based on the documentation:
DefaultIfEmpty:
Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.
So in this case if the sequence is empty, it returns a default value, for example, take a look at this answer:
opencall.Priority = averages.Where(x => x.ProblemCode == opencall.ProblemCode)
.Select(x => x.Priority)
.DefaultIfEmpty("")
.Single();
in this example if the averages is empty, it returns an empty string, But I want to know is there something like an extention method in linq so that if the preperty (x.Priority) is null, returns a default value?
PS: I know we can check that using a if
statement:
opencall.Priority = averages.Where(x => x.ProblemCode == opencall.ProblemCode)
.Select(x => x.Priority)
.DefaultIfEmpty("")
.Single();
if (!string.IsNullOrWhiteSpace(opencall.Priority))
opencall.Priority = "Default value";
...
I'm just curious to know that, Is there any kind of extension method for doing that?
Upvotes: 3
Views: 5649
Reputation: 21795
You can use the same DefaultOrEmpty
method overload to provide the default value. In the above query since we are trying to fetch the Priority
property which is of String
type. You can provide a default value of String in the method overload:-
opencall.Priority = averages.Where(x => x.ProblemCode == opencall.ProblemCode)
.Select(x => x.Priority)
.DefaultIfEmpty("High")
.Single();
This will result in High
for non matching rows.
Upvotes: 2