Combine Two Lists in C#

Combine Two Lists in C#: List operations are essential in C# for managing collections of data. Combining lists simplifies data manipulation, enhances code efficiency, and supports complex operations. This technique is crucial in programming, particularly for tasks like merging datasets, aggregating results, and handling dynamic data structures.

Combine Two Lists in C# Using AddRange() Method

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initialize the first list
        List<int> list1 = new List<int> { 1, 2, 3, 4, 5 };

        // Initialize the second list
        List<int> list2 = new List<int> { 6, 7, 8, 9, 10 };

        // Use AddRange() to combine list2 into list1
        list1.AddRange(list2);

        // Print the combined list
        Console.WriteLine("Combined List:");
        foreach (int item in list1)
        {
            Console.Write(item + " ");
        }
    }
}

Explanation of the Code:

  • The program initializes two lists, list1 and list2, with integers.
  • Call the `AddRange()` method on `list1` to add all elements from `list2` to `list1`.
  • Finally, the program prints the combined list, which includes all elements from both list1 and list2.

Output:

Combined List:
1 2 3 4 5 6 7 8 9 10

Combine Two Lists in C# Using Concat() Method

The code for combining two lists in C# using the Concat() method, along with the example output using alphabets:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // Initialize two lists with alphabets
        List<string> list1 = new List<string> { "A", "B", "C", "D" };
        List<string> list2 = new List<string> { "E", "F", "G", "H" };

        // Combine the lists using Concat() method
        var combinedList = list1.Concat(list2);

        // Output the combined list
        Console.WriteLine("Combined List:");
        foreach (var item in combinedList)
        {
            Console.Write(item + " ");
        }
    }
}

Explanation of the Code:

  1. Initialization: Initialize two lists, `list1` and `list2`, with alphabetic elements.
  2. Combining Lists: The Concat() method is used to concatenate list1 and list2.
  3. Output: The combined list is printed to the console, displaying all elements from both lists in sequence.

Output:

Combined List:
A B C D E F G H 

Combine Two Lists in C# Using Union() Method

Code example for combining two lists in C# using the Union() method:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        // Define two lists
        List<string> list1 = new List<string> { "A", "B", "C" };
        List<int> list2 = new List<int> { 1, 2, 3 };

        // Combine the lists using Union() method
        var combinedList = list1.Cast<object>().Union(list2.Cast<object>()).ToList();

        // Display the combined list
        Console.WriteLine("Combined List:");
        foreach (var item in combinedList)
        {
            Console.WriteLine(item);
        }
    }
}

Explanation of the Code:

  1. Define two lists: The first list contains alphabets, and the second list contains numbers.
  2. Combine the lists using Union() method: The Union() method combines the two lists into one, removing duplicates if any. Here, Cast<object>() is used to handle lists of different types.
  3. Display the combined list: Iterate through the combined list and print each element.

Output:

Combined List:
A
B
C
1
2
3

This example shows how to combine a list of strings and a list of integers into a single list using the Union() method in C#.

Practical Examples of Combining Two Lists in C#

Combining lists is a common operation in programming, especially in data processing, where merging data from different sources is required. Here are some practical examples of combining two lists in C#:

1. Merging Employee and Contractor Lists

In a company, you might have separate lists for employees and contractors. Combining these lists can be useful for generating a comprehensive list of all people associated with the company.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> employees = new List<string> { "Alice", "Bob", "Charlie" };
        List<string> contractors = new List<string> { "Dave", "Eve", "Frank" };

        var allPersonnel = employees.Union(contractors).ToList();

        Console.WriteLine("All Personnel:");
        foreach (var person in allPersonnel)
        {
            Console.WriteLine(person);
        }
    }
}

2. Combining Product Lists from Different Suppliers

In an inventory management system, you may need to combine product lists from different suppliers to get a complete list of products available.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> supplier1Products = new List<string> { "ProductA", "ProductB", "ProductC" };
        List<string> supplier2Products = new List<string> { "ProductD", "ProductE", "ProductF" };

        var allProducts = supplier1Products.Union(supplier2Products).ToList();

        Console.WriteLine("All Products:");
        foreach (var product in allProducts)
        {
            Console.WriteLine(product);
        }
    }
}

3. Consolidating Class Schedules

In educational institutions, combining class schedules from different departments can help in creating a master schedule for the entire institution.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> department1Schedule = new List<string> { "Math", "Physics", "Chemistry" };
        List<string> department2Schedule = new List<string> { "Biology", "History", "Geography" };

        var masterSchedule = department1Schedule.Union(department2Schedule).ToList();

        Console.WriteLine("Master Schedule:");
        foreach (var subject in masterSchedule)
        {
            Console.WriteLine(subject);
        }
    }
}

4. Combining Lists of Registered Participants

For events or competitions, you might need to combine lists of participants registered through different channels.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> onlineRegistrations = new List<string> { "John", "Jane", "Jim" };
        List<string> onSiteRegistrations = new List<string> { "Jake", "Jill", "Janet" };

        var allRegistrations = onlineRegistrations.Union(onSiteRegistrations).ToList();

        Console.WriteLine("All Registrations:");
        foreach (var participant in allRegistrations)
        {
            Console.WriteLine(participant);
        }
    }
}

5. Combining Lists of Customer Orders

In an e-commerce application, combining lists of customer orders from different sales channels (e.g., website, mobile app) helps in analyzing total sales.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> websiteOrders = new List<string> { "Order1", "Order2", "Order3" };
        List<string> mobileAppOrders = new List<string> { "Order4", "Order5", "Order6" };

        var allOrders = websiteOrders.Union(mobileAppOrders).ToList();

        Console.WriteLine("All Orders:");
        foreach (var order in allOrders)
        {
            Console.WriteLine(order);
        }
    }
}

In this blog, we explored various methods to combine two lists in C#, including `Union()`, `AddRange()`, and `Concat()`. Understanding these operations is crucial for efficient programming. Experiment with these techniques to find the best fit for your needs. For more programming insights, check out Newtum’s user-friendly courses and resources. Happy coding!

About The Author

Leave a Reply