繁体   English   中英

如何轻松比较2个以上数组参数的长度?

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

我有一个对象有4个数组参数,所有参数都应该是相同的长度。

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

我想确保所有这些数组在构造函数中的长度相同,但我显然不能这样做

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

所以我去了

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

但是这看起来并不是特别吸引人,如果我删除其中一个数组或其他东西,就不会那么清楚。

我认为必须有一个很好的方法来使用LINQ在它们的集合上执行此操作,但我的数组显然不是可枚举的。 然后我有了创意(也许可能很傻)并想通过我可以用长度初始化一个hashset并检查它的长度是否为1.是否有标准/更好的方法来检查多个数组长度是否相等或者我的&&方法和我一样好可以得到?

如何编写辅助方法?

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

您可以这样称呼:

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

或者,如果您通常使用反向布尔条件,则提供相反的方法可能更具可读性:

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.
}

这是Linq的一种方法

if (new []{arr1.Length, arr2.Length, arr3.Length, arr4.Length}.Distinct().Count() != 1)

您可以检查是否所有符合第一个:

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

另一个(更好)选项是创建一个自定义类,所以你有一个项目适用于所有类型。 然后,您只需创建自定义类的数组: CustomClass[] 由于数据类型已经强制执行,因此无需检查它们是否以相等的长度传入。

我可以看到你有4种类型作为type1到type4。 既然你必须有相同的长度,请考虑以下事项:

public class Custom{

  public Custom(type1 t1, type2 t2, type3 t3, type4 t4){
      this.T1=t1;
      this.T2=t2;
      this.T3=t3;
      this.T4=t4;
  }

  public type1 T1 {get; set;}
  public type2 T2 {get; set;}
  public type3 T3 {get; set;}
  public type4 T4 {get; set;}
}

现在你的Foo类可以有构造函数:

public Foo(
int a,
int b,
params Custom [] array)
{ /* ... */ }

Custom类的唯一构造函数将确保初始化所有type1到4。 您的Foo类中的数组参数将允许您根据需要传递元素。 总体效果将是所有类型1到4的变量在Custom类的数组中的数量相等。

这更像是间接执行等长规则而不是检查长度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM