Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Null coalesce with LINQ

I have 2 classes which looks like this:

class Widget
{
    string Selected { get; set; }

    List<Option> Options { get; set; }
}

class Option
{
    string InternalCode { get; set; }

    string ExternalCode { get; set; }
}

Options gets populated dynamically with different data per client for showing ExternalCode as options

Selected gets populated with ExternalCode.

I then need to access the InternalCode which matches.

At present I am doing this:

var option = widget.Options.SingleOrDefault(o => o.ExternalCode == widget.Selected);

var internalCode = option == null ? string.Empty : option.InternalCode;

Is this possible using a single line using Null Coalesce?

like image 834
Shevek Avatar asked Jan 06 '16 10:01

Shevek


Video Answer


2 Answers

Yes, you can use the null propagation and null coalescing operator, which suits your needs if you can use C# 6:

var option = widget.Options
             .SingleOrDefault(o => o.ExternalCode == widget.Selected)?.InternalCode
             ?? string.Empty;

The ?. will translate to your use of the option == null ? part.

like image 68
Patrick Hofman Avatar answered Oct 16 '22 09:10

Patrick Hofman


Sure, with a small change:

var option = widget.Options
                   .Where(o => o.ExternalCode == widget.Selected)
                   .Select(o => o.InternalCode)
                   .FirstOrDefault() ?? "";

In other words, project the sequence of matching options to a sequence of internal codes, and then take the first of those, defaulting to null... which allows you to use the null-coalescing operator on the result.

You can use the null-conditional operator as per Patrick's answer instead, but personally I'd prefer the code in this answer - I think it's simpler to understand.

like image 9
Jon Skeet Avatar answered Oct 16 '22 09:10

Jon Skeet