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

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


当前回答

我使用的两个选项是:

list1.AddRange(list2);

or

list1.Concat(list2);

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

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

使用Concat解决了这个问题。

其他回答

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

list2.AddRange(list1);

空间开销最小的方法是使用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
*/

一种方法:List.AddRange()取决于类型?

就像这样:

firstList.AddRange (secondList);

或者,你可以使用System.Linq中定义的“Union”扩展方法。 使用'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