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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With