简体   繁体   中英

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. 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. That's useful for multidimensional arrays (or non-0-based arrays), not jagged arrays. Instead, you can use 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 .

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.

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):

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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