将列表复制到新列表-更加高效&最佳实践 [英] copying a list to a new list - More efficient & Best Practice
本文介绍了将列表复制到新列表-更加高效&最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将列表复制到新列表的适当方法是什么?将列表复制到新列表的最有效方法是什么?
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();
或:
List<String>List2 = new List<String>();
foreach (string item in List)
{
List2.Add(item);
}
更新:
效率更高的IL代码又如何呢?
What about more efficient IL code?
推荐答案
ToList的作用(缩短):
What ToList does (shortened):
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
return new List<TSource>(source);
}
列表ctor的作用(简称):
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;
}
因此ToList()效率更高-它确实先分配空间,然后一步一步复制所有项目.
So the ToList() is much more efficient - it does allocate the space first and then copy all items in one step.
这篇关于将列表复制到新列表-更加高效&最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文