-->

C# copy values from array to list

2019-09-20 10:43发布

问题:

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?

回答1:

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.



回答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.



回答3:

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



标签: c# arrays copy lis