如果我有类型字符串(或任何其他类型)的两个列表,什么是连接两个列表的快速方法?
顺序应该保持不变。应该删除重复的内容(尽管两个链接中的每一项都是唯一的)。当我在谷歌上搜索的时候,我并没有找到太多关于这方面的信息,也不想为了加快交付速度而实现任何。net接口。
如果我有类型字符串(或任何其他类型)的两个列表,什么是连接两个列表的快速方法?
顺序应该保持不变。应该删除重复的内容(尽管两个链接中的每一项都是唯一的)。当我在谷歌上搜索的时候,我并没有找到太多关于这方面的信息,也不想为了加快交付速度而实现任何。net接口。
当前回答
有一种方法,我还没有看到提到过,可以更健壮一点,特别是如果你想以某种方式改变每个元素(例如,你想要. 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
*/
就像这样:
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
空间开销最小的方法是使用Concat扩展方法。
var combined = list1.Concat(list2);
它创建了IEnumerable<T>的实例,该实例将按顺序枚举list1和list2的元素。
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);
有一种方法,我还没有看到提到过,可以更健壮一点,特别是如果你想以某种方式改变每个元素(例如,你想要. trim()所有的元素。
List<string> a = new List<string>();
List<string> b = new List<string>();
// ...
b.ForEach(x=>a.Add(x.Trim()));