Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed a test for null in a single LINQ expression

Let's start with a simple example class:

public class Foo
{
    public DateTime Date { get; set; }
    public decimal Price { get; set; }
}

Then create a list:

List<Foo> foos = new List<Foo>;

I would like to return a formatted price or "N/A" of one item in the list based on a date, so for example I could write:

Foo foo = foos.FirstOrDefault(f => f.Date == DateTime.Today);
string s = (foo != null) ? foo.Price.ToString("0.00") : "N/A";

I would like to combine the above 2 lines like the following:

string s = foos.FirstOrDefault(f => f.Date == DateTime.Today).Price.ToString("0.00") ?? "N/A";

However, this does not achieve what I want because if (f => f.Date == DateTime.Today) does not return a Foo then a NullReferenceException is thrown.

Therefore, is it possible with LINQ to create just 1 statement to either return the formatted price or "N/A"?

like image 831
Barry Kaye Avatar asked Dec 03 '22 06:12

Barry Kaye


1 Answers

If you filter first and then select, you can use the null coalescing operator (??) like so:

string price = foos.Where(f => f.Date == DateTime.Today)
                   .Select(f => f.Price.ToString())
                   .FirstOrDefault() ?? "N/A";
like image 85
Allon Guralnek Avatar answered Dec 19 '22 08:12

Allon Guralnek