2009-09-10 24 views
0

是否有可能在C#中用其他列表初始化列表?說我有這些到列表:用於初始化列表<T>與現有列表的語法<T>對象

List<int> set1 = new List<int>() {1, 2, 3}; 
List<int> set2 = new List<int>() {4, 5, 6}; 

我想有是這個代碼的縮寫:

List<int> fullSet = new List<int>(); 
fullSet.AddRange(set1); 
fullSet.AddRange(set2); 

提前感謝!

+0

你說的是.NET的2/3或3.5?這裏的大多數解決方案僅限於3.5。 – Lucero 2009-09-10 12:05:25

回答

8

爲了允許重複的元素(如在您的示例):

List<int> fullSet = set1.Concat(set2).ToList(); 

這可以推廣到多個列表,即...Concat(set3).Concat(set4)。如果你想刪除重複的元素(這兩個列表中出現的項目):

List<int> fullSet = set1.Union(set2).ToList(); 
0
var fullSet = set1.Union(set2); // returns IEnumerable<int> 

如果你想列出<INT>而不是IEnumerable的<INT>你可以這樣做:

1
 static void Main(string[] args) 
     { 
      List<int> set1 = new List<int>() { 1, 2, 3 }; 
      List<int> set2 = new List<int>() { 4, 5, 6 }; 

      List<int> set3 = new List<int>(Combine(set1, set2)); 
     } 

     private static IEnumerable<T> Combine<T>(IEnumerable<T> list1, IEnumerable<T> list2) 
     { 
      foreach (var item in list1) 
      { 
       yield return item; 
      } 

      foreach (var item in list2) 
      { 
       yield return item; 
      } 
     } 
+1

這只是Enumerable.Concat當然... – 2009-09-10 12:04:33

+0

我不知道爲什麼當我第一次回答這個問題時,我以爲OP正在尋找一個2.0解決方案....不知道我從哪裏得到的...... – BFree 2009-09-10 12:06:36