-1

I have following code:

for (int c = 0; c < date_old.Length; c++) 
{
    for (int d = 0; d < date_new.Length; d++)
    {
        newList[c] = data_old[c];

        if (date_old[c] == date_new[d])
        {
            newList[c] = data_new[d];
        }
    }
}

What I'm trying to do is the following:

I have four arrays: date_new, date_old, data_new, data_old and a List called newList. date_old and data_old have the same length and date_new and data_new too. I want to loop through the date arrays check if there are equal date values. While I'm doing this, I want to copy every value from the data_old array to newList. When a value is equal, I want to copy the value at this point from the data_new position into the List. Here I get a OutOfBoundException after the second for loop. What is wrong?

darcyy
  • 5,236
  • 5
  • 28
  • 41
uzi42tmp
  • 271
  • 2
  • 9
  • 22

3 Answers3

2

This exception is thrown when you try to read/write to an array with an index greater than array.Length -1.

Double-check the size of newList.

shA.t
  • 16,580
  • 5
  • 54
  • 111
Florian Schmidinger
  • 4,682
  • 2
  • 16
  • 28
2

Make sure your newList is instantiated as

var newList = new DateTime[Math.Max(date_old.Length, date_new.Length)];

Also make sure the length of date_old equals the length of data_old, same thing for date_new and data_new.

Move newList[c] = data_old[c]; to the outer for loop if you can (i.e. to line 3), it's gonna overwrite your new data assigned to newList.

darcyy
  • 5,236
  • 5
  • 28
  • 41
  • ok I've noticed that he copies too much values into the array even when I move the line. I just want him to copy every value once. – uzi42tmp Nov 07 '14 at 07:48
1
for (int c = 0; c < date_old.Length; c++)
{
     for (int d = 0; d < date_new.Length; d++)
     {
         newList.Add((date_old[c] == date_new[d] ? data_new[d] : data_old[c]));

     }
}

with your list solution and this logic you provided

Florian Schmidinger
  • 4,682
  • 2
  • 16
  • 28