[英]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() 方法:
It is simple yet some clarification required.这很简单,但需要一些说明。
Yes.是的。 It will create new list instance.它将创建新的列表实例。
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.