Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two lists together

Tags:

c#

If I have two lists of type string (or any other type), what is a quick way of joining the two lists?

The order should stay the same. Duplicates should be removed (though every item in both links are unique). I didn't find much on this when googling and didn't want to implement any .NET interfaces for speed of delivery.

like image 553
GurdeepS Avatar asked Oct 06 '09 21:10

GurdeepS


2 Answers

You could try:

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

a.AddRange(b);

MSDN page for AddRange

This preserves the order of the lists, but it doesn't remove any duplicates which Union would do.

This does change list a. If you wanted to preserve the original lists then you should use Concat (as pointed out in the other answers):

var newList = a.Concat(b);

This returns an IEnumerable as long as a is not null.

like image 76
ChrisF Avatar answered Nov 03 '22 18:11

ChrisF


The way with the least space overhead is to use the Concat extension method.

var combined = list1.Concat(list2);

It creates an instance of IEnumerable<T> which will enumerate the elements of list1 and list2 in that order.

like image 130
JaredPar Avatar answered Nov 03 '22 17:11

JaredPar