Search code examples
c#listaddrange

How does List<T>.AddRange actually add the range supplied?


I've looked around for a while now and can't seem to find any documentation that covers my concern.

I am wondering if I should ever be concerned with the order a range supplied to List<T>.AddRange() is added to the collection. I can assume all day that it will be added in the sequential order I supplied; that is, if I supply 0, 8, 5, 2, 9 it shouldn't ever be added in the order of 9, 5, 2, 0, 8 or anything other than 0, 8, 5, 2, 9.

I've ran a test in a console application to determine the results using a post-increment in the AddRange method like so:

List<int> test = new List<int>();
for (int i = 0; i < 30;)
    test.AddRange(new int[] { i++, i++, i++ });

foreach (int i in test)
    Console.WriteLine(i);

This prints in sequential order as I expected it to from zero to 29. However, my concern is that I'm unable to find documentation that shows me exactly how this range is added to the collection. I would assume that it would be something along the lines of:

foreach (int i in range)
    collection.Add(i);

Which would definitely preserve any order I've supplied, but I would like to ensure that this is actually what is occurring, or at least that what is occurring will never reorder the supplied range.


NOTE:

Apparently I haven't had enough coffee yet today and missed it while looking over the documentation for AddRange. Thank you all anyways, at least it's a great question for future readers that may be curious.


Solution

  • The order of the elements in the collection is preserved in the List.

    It's the first line under the section Remarks at: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.addrange?view=netframework-4.7.2