在已经是列表的对象上使用ToList()方法:
array.copyTo
在内部复制元素,后者是(从文档中)O(n)您可以在这里看到list
的构造函数的代码(这就是我们所说的)
它很简单,但需要一些澄清。
>
是的。它将创建新的列表实例。
现在要创建新列表时。它将复制其中的所有项。如果它是valuetype,则复制实际值,如果它是引用类型,则复制该引用。它是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; }
}
}