2009-10-06 170 views
220

如果我有兩個字符串類型(或任何其他類型)的列表,加入這兩個列表的快捷方式是什麼?將兩個列表連接在一起

訂單應該保持不變。應刪除重複項目(儘管兩個鏈接中的每個項目都是唯一的)。在Google上搜索時,我沒有發現太多內容,也不希望爲了交付速度而實現任何.NET接口。

+4

命令是否重要?你想保留重複嗎? – Larsenal 2009-10-06 21:28:16

+1

* [您如何連接C#中的列表?](http://stackoverflow.com/questions/1042219/how-do-you-concatenate-lists-in-c)*。 – 2015-11-22 03:12:38

回答

380

你可以嘗試:

List<string> a = new List<string>(); 
List<string> b = new List<string>(); 

a.AddRange(b); 

MSDN page for AddRange

這將保留該列表的順序,但不會刪除任何重複這Union會做。

確實更改列表a。如果你想保留原來的名單,那麼你應該使用Concat(如在其他的答案中指出):

var newList = a.Concat(b); 

這隻要a不是null返回IEnumerable

+13

沒有人真正瞭解何時使用哪種方法。 AddRange編輯一個列表,添加第二個列表(就像你多次調用.Add(foo)一樣)。 Concat和Union擴展方法不會更改原始列表。他們懶惰地構造一個新的IEnumerable,除非必要,甚至不會訪問原始列表成員。如上所述,聯盟刪除重複,而其他人不重複。 – ShawnFumo 2015-01-02 02:15:34

+2

當其中一個列表爲空時,'concat'不起作用 – Amit 2015-12-18 20:10:27

+3

有誰知道這種方法的複雜性是什麼? (很遺憾,微軟不提供這些重要信息作爲他們的MSDN的一部分) – Jacob 2016-11-14 18:00:26

19

事情是這樣的:

firstList.AddRange (secondList); 

或者,您可以使用在System.Linq的定義的「聯盟」的擴展方法。 使用'聯合',你也可以指定一個比較器,它可以用來指定一個項目是否應該聯合。

像這樣:

List<int> one = new List<int> { 1, 2, 3, 4, 5 }; 
List<int> second=new List<int> { 1, 2, 5, 6 }; 

var result = one.Union (second, new EqComparer()); 

foreach(int x in result) 
{ 
    Console.WriteLine (x); 
} 
Console.ReadLine(); 

#region IEqualityComparer<int> Members 
public class EqComparer : IEqualityComparer<int> 
{ 
    public bool Equals(int x, int y) 
    { 
     return x == y; 
    } 

    public int GetHashCode(int obj) 
    { 
     return obj.GetHashCode(); 
    } 
} 
#endregion 
34

Union方法可能會滿足您的需求。您沒有指定訂單或重複是否重要。這取決於類型List.AddRange():

吃兩個IEnumerables和執行聯合爲在這裏看到:

int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 }; 
int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 }; 

IEnumerable<int> union = ints1.Union(ints2); 

// yields { 5, 3, 9, 7, 8, 6, 4, 1, 0 } 
3

的一種方式?

85

用最少的空間開銷的方法是使用所述的毗連擴展方法。

var combined = list1.Concat(list2); 

它創建的IEnumerable<T>它的實例將枚舉list1的和list2中的元素的順序。

7

只要它們是同一類型的,這是非常簡單的用的AddRange:

list2.AddRange(list1); 
6
var bigList = new List<int> { 1, 2, 3 } 
    .Concat(new List<int> { 4, 5, 6 }) 
    .ToList(); /// yields { 1, 2, 3, 4, 5, 6 } 
+0

我也喜歡。很簡單。謝謝。 – dotnetdev 2009-10-06 22:22:35

+0

我喜歡這個,因爲它不會改變任何一個列表。 – 2015-01-13 02:02:07

10

如果某些項目(S)這兩個列表中存在,您可以使用

var all = list1.Concat(list2).Concat(list3) ... Concat(listN).Distinct().ToList(); 
4
List<string> list1 = new List<string>(); 
list1.Add("dot"); 
list1.Add("net"); 

List<string> list2 = new List<string>(); 
list2.Add("pearls"); 
list2.Add("!"); 

var result = list1.Concat(list2); 
12
targetList = list1.Concat(list2).ToList(); 

它工作正常我認爲是。如前所述,Concat返回一個新序列,並將結果轉換爲List,它完美地完成了這項工作。在使用AddRange方法時,隱式轉換可能會失敗。

1

看到這個link

public class ProductA 
{ 
public string Name { get; set; } 
public int Code { get; set; } 
} 

public class ProductComparer : IEqualityComparer<ProductA> 
{ 

public bool Equals(ProductA x, ProductA y) 
{ 
    //Check whether the objects are the same object. 
    if (Object.ReferenceEquals(x, y)) return true; 

    //Check whether the products' properties are equal. 
    return x != null && y != null && x.Code.Equals(y.Code) && x.Name.Equals(y.Name); 
    } 

public int GetHashCode(ProductA obj) 
{ 
    //Get hash code for the Name field if it is not null. 
    int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode(); 

    //Get hash code for the Code field. 
    int hashProductCode = obj.Code.GetHashCode(); 

    //Calculate the hash code for the product. 
    return hashProductName^hashProductCode; 
} 
} 


    ProductA[] store1 = { new ProductA { Name = "apple", Code = 9 }, 
        new ProductA { Name = "orange", Code = 4 } }; 

    ProductA[] store2 = { new ProductA { Name = "apple", Code = 9 }, 
        new ProductA { Name = "lemon", Code = 12 } }; 

//獲取產品從兩個陣列 //不重複計算。

IEnumerable<ProductA> union = 
    store1.Union(store2); 

foreach (var product in union) 
    Console.WriteLine(product.Name + " " + product.Code); 

/* 
    This code produces the following output: 

    apple 9 
    orange 4 
    lemon 12 
*/ 
0

我只是想測試如何Union作品與重疊的引用類型對象的集合默認的比較。

我的目標是:

class MyInt 
{ 
    public int val; 

    public override string ToString() 
    { 
     return val.ToString(); 
    } 
} 

我的測試代碼:

MyInt[] myInts1 = new MyInt[10]; 
MyInt[] myInts2 = new MyInt[10]; 
int overlapFrom = 4; 
Console.WriteLine("overlapFrom: {0}", overlapFrom); 

Action<IEnumerable<MyInt>, string> printMyInts = (myInts, myIntsName) => Console.WriteLine("{2} ({0}): {1}", myInts.Count(), string.Join(" ", myInts), myIntsName); 

for (int i = 0; i < myInts1.Length; i++) 
    myInts1[i] = new MyInt { val = i }; 
printMyInts(myInts1, nameof(myInts1)); 

int j = 0; 
for (; j + overlapFrom < myInts1.Length; j++) 
    myInts2[j] = myInts1[j + overlapFrom]; 
for (; j < myInts2.Length; j++) 
    myInts2[j] = new MyInt { val = j + overlapFrom }; 
printMyInts(myInts2, nameof(myInts2)); 

IEnumerable<MyInt> myUnion = myInts1.Union(myInts2); 
printMyInts(myUnion, nameof(myUnion)); 

for (int i = 0; i < myInts2.Length; i++) 
    myInts2[i].val += 10; 
printMyInts(myInts2, nameof(myInts2)); 
printMyInts(myUnion, nameof(myUnion)); 

for (int i = 0; i < myInts1.Length; i++) 
    myInts1[i].val = i; 
printMyInts(myInts1, nameof(myInts1)); 
printMyInts(myUnion, nameof(myUnion)); 

輸出是:

overlapFrom: 4 
myInts1 (10): 0 1 2 3 4 5 6 7 8 9 
myInts2 (10): 4 5 6 7 8 9 10 11 12 13 
myUnion (14): 0 1 2 3 4 5 6 7 8 9 10 11 12 13 
myInts2 (10): 14 15 16 17 18 19 20 21 22 23 
myUnion (14): 0 1 2 3 14 15 16 17 18 19 20 21 22 23 
myInts1 (10): 0 1 2 3 4 5 6 7 8 9 
myUnion (14): 0 1 2 3 4 5 6 7 8 9 20 21 22 23 

所以,一切工作正常。

相關問題