简体   繁体   中英

How can I replace the contents of one List<int> with those from another?

I was using two nullable int[]s:

int?[] OriginalPterodactylVals = new int?[NUMBER_OF_BABES_IN_TOYLAND];
int?[] ChangedPterodactylVals = new int?[NUMBER_OF_BABES_IN_TOYLAND];

...and this code to sync them up:

ChangedPterodactylVals.CopyTo(OriginalPterodactylVals, 0);

...but now I've changed the int[]s to Lists and haven't yet found or figured out how to accomplish the same thing.

They will both have the same amount of values in the list at the time one is "copied and pasted" into the other.

You can perform a shallow copy by constructing a new list from your existing list:

list2 = new List<int>(list1);

Note that this creates a new list rather than modifying the list that list2 originally refered to (if any).

Here is an approach that modifies the existing list using AddRange rather than creating a new one:

list2.Clear();
list2.AddRange(list1);

And here's another approach using a for loop. This requires that the lists have the same length, but you stated that this is the case in your question.

for (int i = 0; i < list1.Count; ++i)
{
    list2[i] = list1[i];
}

Have you tried:

OriginalPterodactylVals.Clear();
ChangedPterodactylVals.ForEach(val => { OriginalPterodactylVal.Add(val); });

If you want to initialize a new List from an existing List,

List<int> a;
List<int> b = new List<int>(a);

That approach leverages the List<T> constructor that accepts an IEnumerable<T>

http://msdn.microsoft.com/en-us/library/fkbw11z0.aspx

Note using that constructor, you can also initialize a list from an array

int[] a = new int[42];
List<int> b = new List<int>(a);

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