C# copy values from array to list

强颜欢笑 提交于 2019-12-13 10:19:52

问题


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



来源:https://stackoverflow.com/questions/26795897/c-sharp-copy-values-from-array-to-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!