Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for null returned items

Tags:

c#

linq

Currently i am returning a list of items all have a date range. Some of the appointments have expired and others have not happened yet. I am displaying the appointments that have not expired yet. But i want to check if all appoinments have expired then show the first item.

var curApt = myAppts.Where(d => d.Appt.EndTime > DateTime.UtcNow).First();

If myAppts.Where(d => d.Appt.EndTime > DateTime.UtcNow) == null

var curApt = myAppts.First();

how can i structure this so i consider both cases?

like image 619
Masriyah Avatar asked Feb 22 '26 21:02

Masriyah


1 Answers

FirstOrDefault and the null coalescing operator (??):

var curApt = myAppts.FirstOrDefault(d => d.Appt.EndTime > DateTime.UtcNow)
             ?? myAppts.First();

However, you could make this even less exception prone if you have a default value to show if there is no appointments at all, you could chain the null coalescing operator for that:

var curApt = myAppts.FirstOrDefault(d => d.Appt.EndTime > DateTime.UtcNow)
             ?? myAppts.FirstOrDefault() ?? yourDefault;
like image 185
It'sNotALie. Avatar answered Feb 24 '26 09:02

It'sNotALie.