簡體   English   中英

將兩個列表連接在一起

[英]Joining two lists together

如果我有兩個字符串類型(或任何其他類型)的列表,加入這兩個列表的快速方法是什么?

順序應該保持不變。 應該刪除重復項(盡管兩個鏈接中的每個項目都是唯一的)。 我在谷歌搜索時沒有找到太多關於這個的東西,也不想實現任何 .NET 接口以提高交付速度。

你可以試試:

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

a.AddRange(b);

AddRange MSDN 頁面

這保留了列表的順序,但它不會刪除Union會做的任何重復項。

這確實會更改列表a 如果您想保留原始列表,那么您應該使用Concat (如其他答案中所指出的):

var newList = a.Concat(b);

只要a不為空,就會返回一個IEnumerable

空間開銷最小的方式是使用Concat擴展方式。

var combined = list1.Concat(list2);

它創建了一個IEnumerable<T>的實例,它將按順序枚舉 list1 和 list2 的元素。

Union方法可能會滿足您的需求。 您沒有指定順序或重復是否重要。

取兩個 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 } 

像這樣的東西:

firstList.AddRange (secondList);

或者,您可以使用 System.Linq 中定義的“Union”擴展方法。 使用“聯合”,您還可以指定一個比較器,它可用於指定是否應聯合某個項目。

像這樣:

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
targetList = list1.Concat(list2).ToList();

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

如果兩個列表中都存在某些項目,您可以使用

var all = list1.Concat(list2).Concat(list3) ... Concat(listN).Distinct().ToList();

只要它們的類型相同,使用 AddRange 就非常簡單:

list2.AddRange(list1);

AddRange 方法

aList.AddRange( anotherList );
var bigList = new List<int> { 1, 2, 3 }
    .Concat(new List<int> { 4, 5, 6 })
    .ToList(); /// yields { 1, 2, 3, 4, 5, 6 }
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);

一種方式: List.AddRange()取決於類型?

一種方式,我沒有看到提到可以更健壯一點,特別是如果您想以某種方式更改每個元素(例如,您想要.Trim()所有元素。

List<string> a = new List<string>();
List<string> b = new List<string>();
// ...
b.ForEach(x=>a.Add(x.Trim()));

看這個鏈接

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
*/

我使用的兩個選項是:

list1.AddRange(list2);

要么

list1.Concat(list2);

但是我注意到,當我使用帶有遞歸函數的AddRange方法時,它經常調用自身,因為達到了最大維數,我得到了 SystemOutOfMemoryException。

(消息谷歌翻譯)
數組尺寸超出了支持的范圍。

使用Concat解決了這個問題。

我只是想測試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

所以,一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM