Pages

Thursday, October 22, 2015

Nullable comparisons simplified with LINQ

What if you need to compare few nullable values? For example, you store latest call date and latest email date and need to define the latest contact date - either call or email. The simplest approach in that case probably is

DateTime? callDate, emailDate;

var latestDate = callDate ?? emailDate;
if (callDate.HasValue && emailDate.HasValue)
    latestDate = callDate > emailDate
                ? callDate
                : emailDate;

Simple and straightforward. Especially if you have read Eric Lippert`s blog post about nullable comparisons. But what if you have third option - liveConversationDate? Or something even bigger? Writing all those conditions one by one can be troublesome.
I found that LINQ is the simplest approach. Just combine all values into a list, filter out nulls (or apply your business rules) and order it!

 int? a, b, c;
 a = null;
 b = 5;
 c = 3;
 
 var res = new List<int>() {a, b, c};
 Console.WriteLine(res.OrderByDescending(i => i).First());
 Console.WriteLine(res.OrderBy(i => i).First());
 Console.WriteLine(res.Where(i => i != null).OrderBy(i => i).First());

No comments:

Post a Comment