跳到主要內容

C# 中 List 複製內容到另一個 List 的幾種方法

簡單又實用 ^ ^

* 第一種透過 .ToList( ) 方法:

 List<string> List1 = new List<string>();
 List<string> List2 = new List<string>();

 List1.Add("A");
 List1.Add("B");
 List1.Add("C");
 List1.Add("D");

List2 = List1.ToList( );

* 第二種方式在建立物件時複製前一個 List

 List<string> List1 = new List<string>();

 List1.Add("A");
 List1.Add("B");
 List1.Add("C");
 List1.Add("D");

List<string> List2 = new List<string>(List1);


* 第三種方法新的List 中使用 AddRange( ) 方法

 List<string> List1 = new List<string>();
 List<string> List2 = new List<string>();

 List1.Add("A");
 List1.Add("B");
 List1.Add("C");
 List1.Add("D");

List2.AddRange(List1);

另可使用 List1.GetRange(Start, End) 來複製不固定大小(但不包含End)的內容



留言