是否可以使用C#中的其他List初始化List?说我有这些列表:

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> fullSet = set1.Concat(set2).ToList();

这可以推广到更多列表,即 ... Concat(set3).Concat(set4)。如果要删除重复元素(两个列表中显示的项目):

List<int> fullSet = set1.Union(set2).ToList();

其他提示

        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;
            }
        }
var fullSet = set1.Union(set2); // returns IEnumerable<int>

如果你想要List&lt; int&gt;而不是IEnumerable&lt; int&gt;你可以这样做:

List<int> fullSet = new List<int>(set1.Union(set2));
List<int> fullSet = new List<int>(set1.Union(set2));

可能会有效。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top