Home >Backend Development >C++ >How can I efficiently combine multiple lists in C# while handling duplicates and preserving original lists?

How can I efficiently combine multiple lists in C# while handling duplicates and preserving original lists?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 10:28:18270browse

How can I efficiently combine multiple lists in C# while handling duplicates and preserving original lists?

Combining Multiple Lists Effortlessly

In programming tasks, it's common to encounter the need to merge multiple lists together. Consider the scenario where you have two lists containing strings and desire to combine them efficiently while maintaining the original sequence and eliminating duplicates.

Solution

Fortunately, the .NET framework offers a straightforward solution for this task. Here's the recommended approach:

List<string> a = new List<string>();
List<string> b = new List<string>();

a.AddRange(b);

By utilizing the AddRange method, we can effortlessly append the elements of list b to the end of list a. However, this method does not remove duplicates.

Preserving Original Lists

If altering the original lists is undesirable, we can employ the Concat method:

var newList = a.Concat(b);

This operation creates a new IEnumerable collection that combines the elements of both lists without modifying the originals. It's important to note that if list a is null, the Concat method will return an IEnumerable containing only the elements of list b.

Example Usage

Consider the following example:

List<string> colors1 = new List<string> { "Red", "Blue", "Yellow" };
List<string> colors2 = new List<string> { "Orange", "Pink", "Green" };

Console.WriteLine("Original Lists:");
Console.WriteLine(string.Join(",", colors1));
Console.WriteLine(string.Join(",", colors2));

colors1.AddRange(colors2);
Console.WriteLine("Combined List with Duplicates:");
Console.WriteLine(string.Join(",", colors1));

var colors3 = colors1.Concat(colors2);
Console.WriteLine("Combined List without Duplicates:");
Console.WriteLine(string.Join(",", colors3));

Output:

Original Lists:
Red,Blue,Yellow
Orange,Pink,Green
Combined List with Duplicates:
Red,Blue,Yellow,Orange,Pink,Green,Orange,Pink,Green
Combined List without Duplicates:
Red,Blue,Yellow,Orange,Pink,Green

The code above demonstrates the usage of AddRange and Concat methods to combine lists with and without duplicates.

The above is the detailed content of How can I efficiently combine multiple lists in C# while handling duplicates and preserving original lists?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn