简体   繁体   English

在 IEnumerable 上使用 ToList() 方法<t>这已经是一个列表<t></t></t>

[英]Using ToList() method on IEnumerable<T> which is already a List<T>

Using the ToList() method on IEnumerable which is already a List :已经是 List的 IEnumerable 上使用 ToList() 方法:

  1. Will it create a new List?它会创建一个新的列表吗?
  2. In performance manner: its complexity will still be O(n) or less?在性能方面:它的复杂度仍然是 O(n) 或更少?
  1. It will create a new list.它将创建一个新列表。
  2. It will copy over the elements internally using Array.CopyTo which is (from the docs ) O(n)它将使用Array.CopyTo在内部复制元素,这是(来自文档)O(n)

you can see the code of the constructor of list (which is what is being called) here你可以在这里看到list构造函数的代码(这就是所谓的)

It is simple yet some clarification required.这很简单,但需要一些说明。

  1. Yes.是的。 It will create new list instance.它将创建新的列表实例。

  2. Now when it comes to create new list.现在说到创建新列表。 It will copy all items in it.它将复制其中的所有项目。 If it is valuetype then actual value is being copy and if it is reference type then that ref is being copied.如果它是 valuetype 则实际值正在被复制,如果它是引用类型那么该 ref 正在被复制。 It is O(n).它开着)。

     class Program { static async Task Main(string[] args) { //Value Type List<int> valueTypeitems = new List<int>(); valueTypeitems.Add(1); valueTypeitems.Add(2); var newlist = valueTypeitems.ToList(); valueTypeitems[0] = 3; // This will only reflect in first list. valueTypeitems.ForEach(cc => Console.WriteLine(cc)); newlist.ForEach(cc => Console.WriteLine(cc)); //Reference type List<Test> refItems = new List<Test>(); refItems.Add(new Test() { Value = 1 }); refItems.Add(new Test() { Value = 2 }); var newrefList = refItems.ToList(); refItems.ForEach(cc => Console.WriteLine(cc.Value)); newrefList.ForEach(cc => Console.WriteLine(cc.Value)); refItems[0].Value = 10; //This reflect in both list. As object is same but you change value. refItems.ForEach(cc => Console.WriteLine(cc.Value)); newrefList.ForEach(cc => Console.WriteLine(cc.Value)); //if you actually change ref in one list then it will not reflect refItems[0] = new Test() { Value = 30 }; refItems.ForEach(cc => Console.WriteLine(cc.Value)); newrefList.ForEach(cc => Console.WriteLine(cc.Value)); Console.ReadLine(); } public class Test { public int Value { get; set; } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM