Replace null in DateTime? [] With DateTime.MaxValue using LINQ

How can I replace all DateTime? to a null date on DateTime.MaxValue ?

I tried:

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

and:

 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 get an InvalidOperationException because a.Value is null ...

+4
source share
3 answers

Program the dates into a new array using Enumerable.Select :

 var newArray = myDateTimeArray.Select(x => x ?? DateTime.MaxValue).ToArray(); 

The null-coalescing ( ?? ) operator returns the left operand if it is not null, otherwise it returns the right operand.

+3
source

You can do it:

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

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

+7
source

The Enumerable.Min Method does not have an overload that takes a set of DateTime values ​​(or DateTime? ). You can use the Enumerable.Aggregate Method to implement your own Min method:

 DateTime? result = myDateTimeArray.Where(x => x != null) .DefaultIfEmpty(null) .Aggregate((x, y) => x < y ? x : y); 

Returns null if myDateTimeArray empty or all elements in myDateTimeArray are null , or the minimum DateTime in myDateTimeArray otherwise.

0
source

Source: https://habr.com/ru/post/1483161/


All Articles