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?
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With