Let's start with a simple class of examples:
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 the formatted price or "N / A" of one item in the list based on the 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 following two lines as shown below:
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 Foo, then a NullReferenceException is NullReferenceException .
Therefore, is it possible for LINQ to create only 1 instruction to return a formatted price or "N / A"?
source share