markzzz markzzz - 19 days ago 5
C# Question

How to return empty string if an object is null?

Here is a snippet of my code:

var link = socials.Where(p => p.type == Facebook).FirstOrDefault().URL;


the problem is that there aren't any social object in the list,
FirstOrDefault()
return
null
, and
.URL
trigger an exception.

How can I avoid this in "one" line with LINQ? Thus, if null return empty
""
(or custom even better) string, else
.URL
?

Answer

You can use DefaultIfEmpty with an argument to specify the fallback value:

var link = socials
    .Where(p => p.type == Facebook)
    .Select(p => p.Url)
    .DefaultIfEmpty("")
    .First();

FirstOrDefault is not necessary anymore, it is safe to use First with DefaultIfEmpty.

Comments