HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Joining two lists together

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
togethertwolistsjoining

Problem

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.

Solution

You could try:

List a = new List();
List b = new List();

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.

Code Snippets

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

a.AddRange(b);
var newList = a.Concat(b);

Context

Stack Overflow Q#1528171, score: 778

Revisions (0)

No revisions yet.