如果我有类型字符串(或任何其他类型)的两个列表,什么是连接两个列表的快速方法?
顺序应该保持不变。应该删除重复的内容(尽管两个链接中的每一项都是唯一的)。当我在谷歌上搜索的时候,我并没有找到太多关于这方面的信息,也不想为了加快交付速度而实现任何。net接口。
如果我有类型字符串(或任何其他类型)的两个列表,什么是连接两个列表的快速方法?
顺序应该保持不变。应该删除重复的内容(尽管两个链接中的每一项都是唯一的)。当我在谷歌上搜索的时候,我并没有找到太多关于这方面的信息,也不想为了加快交付速度而实现任何。net接口。
当前回答
一种方法:List.AddRange()取决于类型?
其他回答
我使用的两个选项是:
list1.AddRange(list2);
or
list1.Concat(list2);
然而,我注意到,当我使用递归函数使用AddRange方法时,它经常调用自己,我得到了一个SystemOutOfMemoryException,因为达到了最大维度数。
(消息谷歌翻译后) 数组尺寸超出支持范围。
使用Concat解决了这个问题。
var bigList = new List<int> { 1, 2, 3 }
.Concat(new List<int> { 4, 5, 6 })
.ToList(); /// yields { 1, 2, 3, 4, 5, 6 }
请看这个链接
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
*/
如果两个列表中都有一些项目,你可以使用
var all = list1.Concat(list2).Concat(list3) ... Concat(listN).Distinct().ToList();
只要它们是同一类型的,用AddRange就很简单:
list2.AddRange(list1);