Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to easily compare length of more than 2 array arguments?

Tags:

arrays

c#

I have an object which has 4 array parameters that are all supposed to be the same length.

public Foo(
    int a,
    int b,
    type1[] arr1,
    type2[] arr2,
    type3[] arr3,
    type4[] arr4
    ){ /* ... */ }

I want to ensure that all of these arrays are the same length in the constructor, but I obviously can't do

if (!(arr1.Length == arr2.Length == arr3.Length == arr4.Length))

so I went with

if (!(arr1.Length == arr2.Length && arr2.Length == arr3.Length && 
      arr3.Length == arr4.Length))

but this isn't particularly appealing to look at, and wouldn't be so clear to change if I removed one of the arrays or something.

I figured there must be a nice way to use LINQ to do this on the collection of them, but my arrays are obviously not in an enumerable. Then I got creative (and probably silly) and figured I could initialize a hashset with the lengths and check if it's length is 1. Is there a standard / better way to check multiple array lengths for equality or is my && method as good as I can get?

like image 370
Eric Hansen Avatar asked Oct 25 '25 15:10

Eric Hansen


2 Answers

How about writing a helper method?

public static class Arrays
{
    public static bool AreAllTheSameLength(params Array[] arrays)
    {
        return arrays.All(a => a.Length == arrays[0].Length);
    }
}

Which you could call like so:

if (!Arrays.AreAllTheSameLength(arr1, arr2, arr3, arr4))
{
    // Throw or whatever.
}

Or if you usually use the reversed boolean condition, it may be more readable to provide the opposite method:

public static class Arrays
{
    public static bool HaveDifferingLengths(params Array[] arrays)
    {
        return arrays.Any(a => a.Length != arrays[0].Length);
    }
}

...

if (Arrays.HaveDifferingLengths(arr1, arr2, arr3, arr4))
{
    // Throw or whatever.
}
like image 194
Matthew Watson Avatar answered Oct 27 '25 06:10

Matthew Watson


You can check if all comply to the first one:

if ( new int[]{ arr2.Length
              , arr3.Length
              , arr4.Length
              }
              .Any(n => n != arr1.Length)
   )

Another (better) option would be to create a custom class, so you have one item for all types. Then you can simply create an array of your custom class: CustomClass[]. No need to check if they are passed in with equal length since the data type enforces that already.

like image 25
Patrick Hofman Avatar answered Oct 27 '25 06:10

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!