How to merge two Lists in C#

3 Answers

0 votes
using System;
using System.Collections.Generic;

class MergeTwoLists
{
    static void Main() {
        List<int> list1 = new() { 1, 0, 6, 2, 8, 2, 3, 5, 4 };
        List<int> list2 = new() { 3, 5, 9, 4, 2, 0, 1, 8, 6 };

        list1.AddRange(list2);
 
        foreach (int num in list1) {
            Console.Write(num + " ");
        }
    }
}

 
 
/*
run:

1 0 6 2 8 2 3 5 4 3 5 9 4 2 0 1 8 6 
  
*/

 



answered Jun 27, 2024 by avibootz
edited Jun 27, 2024 by avibootz
0 votes
using System;
using System.Linq;
using System.Collections.Generic;
 
class MergeTwoLists
{
    static void Main() {
        List<int> list1 = new() { 1, 0, 6, 2, 8, 2, 3, 5, 4 };
        List<int> list2 = new() { 3, 5, 9, 4, 2, 0, 1, 8, 6 };
 
        /*
            public static System.Collections.Generic.IEnumerable<TSource> Concat<TSource> (
                this System.Collections.Generic.IEnumerable<TSource> first, 
                System.Collections.Generic.IEnumerable<TSource> second);
        */
        
        var merged = list1.Concat(list2);
 
        foreach (int num in merged) {
            Console.Write(num + " ");
        }
    }
}
 
  
  
/*
run:
 
1 0 6 2 8 2 3 5 4 3 5 9 4 2 0 1 8 6 
   
*/

 



answered Jun 27, 2024 by avibootz
edited Jun 27, 2024 by avibootz
0 votes
using System;
using System.Linq;
using System.Collections.Generic;
 
class MergeTwoLists
{
    static void Main() {
        List<int> list1 = new() { 1, 0, 6, 2, 8, 2, 3, 5, 4 };
        List<int> list2 = new() { 3, 5, 9, 4, 2, 0, 1, 8, 6 };
        
        /*
            public static System.Collections.Generic.IEnumerable<TSource> Union<TSource> (
                this System.Collections.Generic.IEnumerable<TSource> first, 
                System.Collections.Generic.IEnumerable<TSource> second);
        */
        
        IEnumerable<int> union = list1.Union(list2);
  
        foreach (int num in union) {
            Console.Write(num + " ");
        }
    }
}
 
  
  
/*
run:
 
1 0 6 2 8 3 5 4 9 
   
*/

 



answered Jun 27, 2024 by avibootz
edited Jun 27, 2024 by avibootz
...