.NET:结合两个通用列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2002770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET: Combining two generic lists
提问by JamesBrownIsDead
Let's say I have two generic lists of the same type. How do I combine them into one generic list of that type?
假设我有两个相同类型的通用列表。如何将它们组合成该类型的一个通用列表?
回答by Timo Willemsen
This should do the trick
这应该可以解决问题
List<Type> list1;
List<Type> list2;
List<Type> combined;
combined.AddRange(list1);
combined.AddRange(list2);
回答by Guffa
You can simply add the items from one list to the other:
您可以简单地将一个列表中的项目添加到另一个列表中:
list1.AddRange(list2);
If you want to keep the lists and create a new one:
如果您想保留列表并创建一个新列表:
List<T> combined = new List<T>(list1);
combined.AddRange(list2);
Or using LINQ methods:
或者使用 LINQ 方法:
List<T> combined = list1.Concat(list2).ToList();
You can get a bit better performance by creating a list with the correct capacity before adding the items to it:
您可以通过在添加项目之前创建具有正确容量的列表来获得更好的性能:
List<T> combined = new List<T>(list1.Count + list2.Count);
combined.AddRange(list1);
combined.AddRange(list2);
回答by Rafa Castaneda
If you're using C# 3.0/.Net 3.5:
如果您使用的是 C# 3.0/.Net 3.5:
List<SomeType> list1;
List<SomeType> list2;
var list = list1.Concat(list2).ToList();

