C# 使用现有列表对象初始化列表的语法
是否可以用C中的其他列表初始化列表?假设我有以下列表:C# 使用现有列表对象初始化列表的语法,c#,list,syntax,initialization,C#,List,Syntax,Initialization,是否可以用C中的其他列表初始化列表?假设我有以下列表: List<int> set1 = new List<int>() {1, 2, 3}; List<int> set2 = new List<int>() {4, 5, 6}; 我想要的是这个代码的简写: List<int> fullSet = new List<int>(); fullSet.AddRange(set1); fullSet.AddRange(set2)
List<int> set1 = new List<int>() {1, 2, 3};
List<int> set2 = new List<int>() {4, 5, 6};
我想要的是这个代码的简写:
List<int> fullSet = new List<int>();
fullSet.AddRange(set1);
fullSet.AddRange(set2);
提前谢谢
var fullSet = set1.Union(set2); // returns IEnumerable<int>
如果希望使用列表而不是IEnumerable,可以执行以下操作:
List<int> fullSet = new List<int>(set1.Union(set2));
可能有效。允许重复元素,如您的示例所示:
static void Main(string[] args)
{
List<int> set1 = new List<int>() { 1, 2, 3 };
List<int> set2 = new List<int>() { 4, 5, 6 };
List<int> set3 = new List<int>(Combine(set1, set2));
}
private static IEnumerable<T> Combine<T>(IEnumerable<T> list1, IEnumerable<T> list2)
{
foreach (var item in list1)
{
yield return item;
}
foreach (var item in list2)
{
yield return item;
}
}
List<int> fullSet = set1.Concat(set2).ToList();
你说的是.NET2/3还是3.5?这里的大多数解决方案只针对3.5。我不知道为什么我第一次回答这个问题时,我认为OP是在寻找2.0解决方案。。。。不知道我从哪里得到的。。。。。
List<int> fullSet = set1.Concat(set2).ToList();
List<int> fullSet = set1.Union(set2).ToList();