How do I clone a generic list in C#?

前端 未结 26 2378
失恋的感觉
失恋的感觉 2020-11-22 01:27

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()

26条回答
  •  有刺的猬
    2020-11-22 02:12

    To clone a list just call .ToList(). This creates a shallow copy.

    Microsoft (R) Roslyn C# Compiler version 2.3.2.62116
    Loading context from 'CSharpInteractive.rsp'.
    Type "#help" for more information.
    > var x = new List() { 3, 4 };
    > var y = x.ToList();
    > x.Add(5)
    > x
    List(3) { 3, 4, 5 }
    > y
    List(2) { 3, 4 }
    > 
    

提交回复
热议问题