Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello everyone,
if i have List1, List2, List3, List4, List5, List6,

How can i copy all the values inside each list in a new List( ListTotal)

Thanks in advance
Posted

You can use AddRange[^] property if you don't want to use linq:

C#
var l1 = new List<string> {"a", "b"};
var l2 = new List<string> {"c", "d"};

var res = new List<string>();
res.AddRange(l1);
res.AddRange(l2);
 
Share this answer
 
the Union() extension method.

newList = list1.Union(list2).Union(list3);

I should point out that Union() filters out duplicates. If you want duplicates or know there are nonde, use Concat().
 
Share this answer
 
v2
You can try this C# 2.0 solution (no LINQ is required here).
C#
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create sample lists
            var list1 = new List<string> { "A", "B", "C" };
            var list2 = new List<string> { "D", "E" };
            var list3 = new List<string> { "F", "G", "H" };

            // "Concatenate" lists into one enumeration
            var e4 = ConcatLists(list1, list2, list3);

            // Create one list from enumerable sequence
            var l4 = new List<string>(e4);

            // Print items
            foreach (var item in l4)
                Console.WriteLine(item);

            // Wait
            Console.ReadKey();
        }

        public static IEnumerable<T> ConcatLists<T>(params List<T>[] lists)
        {
            foreach (var list in lists)
            {
                foreach (var item in list)
                {
                    yield return item;
                }
            }
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900