Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 353
markzzz Avatar asked Sep 07 '25 17:09

markzzz


2 Answers

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.

like image 87
Tim Schmelter Avatar answered Sep 09 '25 06:09

Tim Schmelter


Another option is to use null coalesce operator

var link = (socials
    .Where(p => p.type == Facebook)
    .Select(p => p.Url)
    .FirstOrDefault()) ?? string.empty;

I understood that string.empty is preferred over "" but that may not be the case - see comment below.

UPDATE In C# 6 there is a null conditional operator (also known as the "Elvis" operator):

var link = socials
    .Where(p => p.type == Facebook)
    .Select(p => p.Url)
    .FirstOrDefault()?.URL ?? string.empty;

A simple example:

stringbuilder sb = null;
// do work
string s = sb?.ToString() ?? "no values found"; 
like image 26
Peter Smith Avatar answered Sep 09 '25 06:09

Peter Smith