JCCyC
JCCyC

Reputation: 16622

How to splice two C# lists into one? Or maybe use a different collection type?

List<string> list1 = new List<string>();
list1.Add("Blah");
list1.Add("Bleh");
list1.Add("Blih");

List<string> list2 = new List<string>();
list2.Add("Ooga");
list2.Add("Booga");
list2.Add("Wooga");

Is there a method to create a third list that has {"Blah", "Bleh", "Blih", "Ooga", "Booga", "Wooga"} or, alternatively, change list1 so it has the three additional elements in list2?

Upvotes: 1

Views: 1224

Answers (3)

TcKs
TcKs

Reputation: 26632

With LINQ, you can do:

List<string> list1 = new List<string>();
list1.Add("Blah");
list1.Add("Bleh");
list1.Add("Blih");

List<string> list2 = new List<string>();
list2.Add("Ooga");
list2.Add("Booga");
list2.Add("Wooga");

var finalList = list1.Concat( list2 ).ToList();

Upvotes: 8

Andrew Siemer
Andrew Siemer

Reputation: 10278

Take a look at the Union() method of a List.

Upvotes: 1

Eugeniu Torica
Eugeniu Torica

Reputation: 7574

I guess this is the solution:

list1.AddRange(list2)

Upvotes: 8

Related Questions