c#中比较3个数组长度的好方法
本文关键字:方法 数组 比较 3个 | 更新日期: 2023-09-27 17:54:59
我有3个数组。我要检查这些数组的长度是否相同。有没有一种聪明又好的方法来比较呢?
为什么不
if (array1.Length == array2.Length && array1.Length == array3.Length)
{
}
如果你有N
数组,你可以这样做:
var a1 = new int[] { 1, 2, 3 };
var a2 = new int[] { 1, 2, 3 };
var a3 = new int[] { 1, 2, 3 };
var arr = new[] { a1, a2, a3 }; // group them all in one array
// check if all arrays have the same length as the first
var test = arr.All(x => x.Length == a1.Length);
bool EqualLengths = Arr1.Length == Arr2.Length && Arr2.Length == Arr3.Length;
我怀疑这算不算聪明和好,但我不认为有什么比这更好的了!
object[] a, b, c;
return (a.Length == b.Length && b.Length == c.Length);
比if (array1.Length == array2.Length && array1.Length == array3.Length)
更简单?
bool success = false;
var arr1 = new[] { "1", "2", "3" };
var arr2 = new[] { "1", "2", "3" };
var arr3 = new[] { "1", "2", "3" };
if (arr1.Length == arr2.Length)
{
if (arr2.Length == arr3.Length)
{
success = true;
}
}
simple
if (array.Length == array1.Length && array1.Length== array2.Length)
{
// do something
}
// compares all arrays passed in for equal length.
// requires at least two arrays so that comparison can be made,
// otherwise this operation would not matter
bool AreEqualLength(Array a1, Array a2, params Array[] arrs) {
if (a1.Length != a2.Length) return false;
foreach(var arr in arrs)
if (arr.Length != a1.Length)
return false;
return true;
}
int[] a1, a2, a3;
a1 = new int[3];
a2 = new int[1];
a3 = new int[1];
bool equalLength = (a1.Length == (a2.Length & a3.Length));