markzzz markzzz - 9 months ago 38
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,
, and
trigger an exception.

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

Answer Source

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

var link = socials
    .Where(p => p.type == Facebook)
    .Select(p => p.Url)

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