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

86 Views Asked by At

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
3

There are 3 best solutions below

0
Tim Schmelter On BEST ANSWER

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));
2
Lanorkin On

Looks like this is one of the cases where LINQ looks cool but not really needed.

Good old foreach might be better from performance and readability perspective, like this:

public static bool IsLengthMismatch(this string[][] arrays)
{
    int? lastLength = -1;

    foreach (var array in arrays)
    {
        if (lastLength != -1 && lastLength != array?.Length)
        {
            return true;
        }

        lastLength = array?.Length;
    }

    return false;
}
0
Custer Murwamuila On

Checks if at least one of the arrays is not null using the Any LINQ method.

string[][] allMyArrays = new string[][] { myArray1, myArray2, myArray3 };

bool atLeastOneNotNull = allMyArrays.Any(arr => arr != null);
bool allHaveEqualLength = allMyArrays.All(arr => arr?.Length == allMyArrays[0]?.Length);

bool lengthMismatch = atLeastOneNotNull && !allHaveEqualLength;

// lengthMismatch will be false if any, but not all arrays are null, and one or more array(s) have unequal lengths.