Search code examples
c#arrayslinqstring-length

C# Check if any element in an Array Group is Null before comparing length


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

  1. Any, but not all arrays are null
  2. One or more array(s) length are not equal

Solution

  • 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));