简体   繁体   English

如何比较锯齿状阵列中的项目?

[英]How can I compare items in a jagged array?

I would like to create a jagged array of a certain type, and then create another array from that based on comparisons between two items in the array. 我想创建某种类型的锯齿状数组,然后根据该数组中两个项目之间的比较从中创建另一个数组。

For example: 例如:

int[][] arr = new int[][] 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22},
    new int[] {0,2,4,6}
};

int[][] arrResult = new int[arr.GetUpperBound(0)][]; 

for (int i = 0; i < arr.GetUpperBound(0); i++)
{
    for (int j = 0; j < arr[i].Length; j++)
    {
        arrResult[i][j] = arr[i][j] + arr[i + 1][j];
    }
}

I'm not sure how to say that if i+1 doesn't exist, then skip that comparison. 我不知道该怎么说,如果i + 1不存在,那就跳过那个比较。 Or is there a better way to do this? 还是有更好的方法来做到这一点?

EDIT 编辑

By compare I mean I want to access two items from the array that come after each other in column, do something with them and create an entry into a new array (with the same structure) from the product. 相比之下,我的意思是我想访问数组中排在列中的两个项目,对它们进行处理,然后从产品创建一个进入新数组(具有相同结构)的条目。

You are not comparing but adding. 您不是在比较而是在添加。 So it is not clear what you really want to do. 因此尚不清楚您真正想要做什么。

If you want to perform an operation on corresponding items in two consecutive rows, you can do so only for the minimum length of the two rows 如果要对连续两行中的对应项执行操作,则只能对两行的最小长度执行操作

for (int i = 0; i < arr.Length - 1); i++) {
    for (int j = 0; j < arr[i].Length && j < arr[i + 1].Length; j++) {
        arrResult[i][j] = arr[i][j] + arr[i + 1][j];
    } 
} 

First, you don't need GetUpperBound() here. 首先,这里不需要GetUpperBound() That's useful for multidimensional arrays (or non-0-based arrays), not jagged arrays. 这对于多维数组(或非基于0的数组)而不是锯齿状数组很有用。 Instead, you can use Length - 1 . 相反,您可以使用Length - 1

Second, you need to create the arrays you're assigning to. 其次,您需要创建要分配给的数组。 new int[count][] doesn't create the nested arrays, so your code would throw a NullReferenceException . new int[count][]不会创建嵌套数组,因此您的代码将抛出NullReferenceException

Third, you want to limit the index (and the size of the created array) by the smaller of the two sizes. 第三,您希望通过两个大小中较小的一个来限制索引(以及创建的数组的大小)。 You can use Math.Min() for that. 您可以Math.Min()使用Math.Min()

Put together: 放在一起:

int[][] arrResult = new int[arr.Length - 1][]; 

for (int i = 0; i < arr.Length - 1; i++)
{
    int length = Math.Min(arr[i].Length, arr[i+1].Length);
    arrResult[i] = new int[length];

    for (int j = 0; j < length; j++)
    {
        arrResult[i][j] = arr[i][j] + arr[i + 1][j];
    }
}

Fourth, as an alternative, you could use LINQ Zip() (it will take care of limiting the size of the result by the shorter array): 第四,作为替代,您可以使用LINQ Zip() (它将通过较短的数组来限制结果的大小):

int[][] arrResult = new int[arr.Length - 1][]; 

for (int i = 0; i < arr.Length - 1; i++)
{
    arrResult[i] = arr[i].Zip(arr[i+1], (a, b) => a + b).ToArray();
}

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

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