In C for adding a list to another list, can be used addRange or Concat method. You can concatenate Lists in C# by following ways.
AddRange: Adds the elements of the specified collection to the end of the List<T>.
Example 1: Can be used this code joining two lists together
1 2 3 | list1.AddRange(list2); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Program { static void Main(string[] args) { List<string> list1 = new List<string> { "Manchester City", "Manchester United", "Everton","Chelsea" }; List<string> list2 = new List<string> { "Liverpool", "Newcastle United" }; list1.AddRange(list2); foreach (var item in list1) { Console.WriteLine(item); } Console.ReadLine(); } } |
Concat: Concatenates two sequences.
Example 2: Concatenates two sequences via LINQ syntax
1 2 3 | IEnumerable<string> query = list1.Select(x => x ).Concat(list2.Select(y => y)); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Program { static void Main(string[] args) { List<string> list1 = new List<string> { "Manchester City", "Manchester United", "Everton","Chelsea" }; List<string> list2 = new List<string> { "Liverpool", "Newcastle United" }; IEnumerable<string> query = list1.Select(x => x ).Concat(list2.Select(y => y)); foreach (string name in query) { Console.WriteLine(name); } Console.ReadLine(); } } |
Example 3: Only using concat method (Simplest way)
1 2 3 | var list3 = list1.Concat(list2); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Program { static void Main(string[] args) { List<string> list1 = new List<string> { "Manchester City", "Manchester United", "Everton","Chelsea" }; List<string> list2 = new List<string> { "Liverpool", "Newcastle United" }; var list3 = list1.Concat(list2); foreach (string name in list3) { Console.WriteLine(name); } Console.ReadLine(); } } |
Output: