Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append LinkedList to the end of another LinkedList? [duplicate]

Tags:

c#

Let's say I have the following:

LinkedList<int> list1 = new LinkedList<int>();
LinkedList<int> list2 = new LinkedList<int>();

list1.AddLast(1);
list1.AddLast(2);

list2.AddLast(1);
list2.AddLast(2);

As far as I know you cannot do the following;

list1.AddLast(list2.First);

and except the lists to be connected together.

What is the proper way to merge two LinkedLists in C#? I know there is a Union() method, but it seems like such strong point of LinkedList in C++ is that you can easily combine and break lists apart if need be.

The LinkedList class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state.

like image 276
afuzzyllama Avatar asked Nov 15 '25 16:11

afuzzyllama


1 Answers

It's equally simple if you use a List instead of a LinkedList. Here are a couple of ways to do the whole list.

LINQ;

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

Other way I found on msdn;

List<int> combinedList = new List<int>();
combinedList.AddRange(list1);
combinedList.AddRange(list2);
like image 190
evanmcdonnal Avatar answered Nov 17 '25 09:11

evanmcdonnal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!