I have a statement that compares the length of elements in all string arrays.
string[][] allMyArrays= new string[][] { myArray1, myArray2, myArray3 };
lengthMismatch = allMyArrays.GroupBy(x => x.Length).Count() > 1;
However, null exception
hits if any of them are null
.
How can I get result that lengthMismatch
= false
if
You could use:
bool lengthMismatch = allMyArrays.GroupBy(x => x?.Length ?? int.MinValue).Count() > 1;
On this way you still differrentiate between an empty array and a null array. If all are null this is false
as desired.
You could also use an optimized way avoiding GroupBy
on the whole array:
int firstLength = allMyArrays.FirstOrDefault()?.Length ?? int.MinValue;
bool anyDifferentLength = allMyArrays.Skip(1)
.Any(arr => firstLength != (arr?.Length ?? int.MinValue));