如果我有类型字符串(或任何其他类型)的两个列表,什么是连接两个列表的快速方法?

顺序应该保持不变。应该删除重复的内容(尽管两个链接中的每一项都是唯一的)。当我在谷歌上搜索的时候,我并没有找到太多关于这方面的信息,也不想为了加快交付速度而实现任何。net接口。


当前回答

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);

其他回答

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 } 

空间开销最小的方法是使用Concat扩展方法。

var combined = list1.Concat(list2);

它创建了IEnumerable<T>的实例,该实例将按顺序枚举list1和list2的元素。

请看这个链接

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

只要它们是同一类型的,用AddRange就很简单:

list2.AddRange(list1);

我使用的两个选项是:

list1.AddRange(list2);

or

list1.Concat(list2);

然而,我注意到,当我使用递归函数使用AddRange方法时,它经常调用自己,我得到了一个SystemOutOfMemoryException,因为达到了最大维度数。

(消息谷歌翻译后) 数组尺寸超出支持范围。

使用Concat解决了这个问题。