articles » current » dot-net » join-two-enumerables

.NET: Join/Merge Two List, Array or Enumerable (IEnumerable) Objects

How to combine Lists, Arrays or Enumerables and, optionally, make them unique or distinct using C#.

.NET makes combining Arrays, Lists or Enumerables easy. Use either AddRange() or Concat() to merge, then use Distinct() to make Enumerables with unique values.

See the notes in the code for more information.


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

namespace ConsoleApp1
{
	class Program
	{
		static void Main(string[] args)
		{
			var list = new List<int>() { 1, 2, 3 };
			var array = new int[] { 3, 4, 5 };
			list.AddRange(array); // NOTE: Use AddRange(); an Array is not required - this can also be another Enumerable such as a List
			foreach (var i in list)
			{
				Console.WriteLine(i);
			}

			Console.WriteLine();

			var list2 = new List<int>() { 5, 6, 7 };
			IEnumerable<int> combined = list.Concat(list2); // NOTE: Use Concat() which requires System.Linq and so returns an IEnumerable which can be converted to a List or Array using ToList() and ToArray() methods, respectively
			foreach (var i in combined)
			{
				Console.WriteLine(i);
			}


			Console.WriteLine();

			IEnumerable<int> distinct = combined.Distinct(); // NOTE: If wanting to make the list of values unique or distinct, use Distinct() which requires System.Linq
			foreach (var i in distinct)
			{
				Console.WriteLine(i);
			}
		}
	}
}

The output looks like this:

1
2
3
3
4
5

1
2
3
3
4
5
5
6
7

1
2
3
4
5
6
7

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE