简体   繁体   中英

returning default value if a property is null

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM