Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying a list to a new list - More efficient & Best Practice

Tags:

c#

What is the appropriate way of copying a list to a new list? And What is the most efficient way of copying a list to a new list?

By efficient, not code efficiency, more in the behind the scenes framework sense.

List<String>List2 = List.ToList();

Or:

List<String>List2 = new List<String>();
foreach (string item in List)
{
 List2.Add(item);
}

Update:

What about more efficient IL code?

like image 329
webdad3 Avatar asked Jul 10 '13 13:07

webdad3


People also ask

How to copy list into another list Python?

Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 seconds to complete.

Can you set a list equal to another list?

A list is equal to another list if the two lists are the same type, contain the same number of elements, and the elements occur in the same order.


2 Answers

Given that List<T> has an IEnumerable<T> constructor, I would prefer this form:

List<string> newList = new List<string>(otherList);

Edit

And as Ondrej points out in the decompiled code below, the constructor of List<T> preallocates the size of the array and copies the contents over. This is going to be much quicker than creating a new list and then iterating over the other list adding items individually, especially as in your 2nd example you're not specifying how many items to preallocate.

like image 84
Moo-Juice Avatar answered Oct 29 '22 17:10

Moo-Juice


What ToList does (shortened):

public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
    return new List<TSource>(source);
}

What List ctor does (shortened):

public List(IEnumerable<T> collection)
{
    ICollection<T> collection2 = collection as ICollection<T>;
    int count = collection2.Count;
    this._items = new T[count];
    collection2.CopyTo(this._items, 0);
    this._size = count;
}

So the ToList() is much more efficient - it does allocate the space first and then copy all items in one step.

like image 45
Ondrej Svejdar Avatar answered Oct 29 '22 17:10

Ondrej Svejdar