Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace null in a DateTime?[] with DateTime.MaxValue using LINQ

How can I replace all DateTime?s where the date is null with DateTime.MaxValue?

I have tried:

Array.ConvertAll(myDateTimeArray, a => a = a.HasValue ? a : DateTime.MaxValue);

and also:

myDateTimeArray.Where(a => a == null).ToList().ForEach(a => a = DateTime.MaxValue);

After that I want to do something like:

DateTime minDate = myDateTimeArray.Min(a => a.Value);

but I am getting an InvalidOperationException because a.Value is null...

like image 481
huzle Avatar asked Dec 27 '22 03:12

huzle


1 Answers

You can do this:

myDateTimeArray = myDateTimeArray.Select(dt => dt ?? DateTime.MaxValue).ToArray();

This would replace the entire array, not its individual elements. If you need to replace individual elements, use a for loop instead.

like image 51
Sergey Kalinichenko Avatar answered Jan 31 '23 08:01

Sergey Kalinichenko