Matt Matt - 1 year ago 71
C# Question

How do you concatenate Lists in C#?

If I have:

List<string> myList1;
List<string> myList2;
int placeToCheckValues = 0; //Used for breakpoints since the values don't get updated until after the line is executed

myList1 = getMeAList();
placeToCheckValues = 0; //Checked myList1 here, it contains 4 strings

myList2 = getMeAnotherList();
placeToCheckValues = 0; //Checked myList2 here, it contains 6 strings

placeToCheckValues = 0; //Checked mylist1 again, it contains 4 strings... why?

I ran code similar to this in Visual Studio 2008 and set break points after each execution. After
myList1 = getMeAList();
contains four strings, and I pressed the plus button to make sure they weren't all nulls.

myList2 = getMeAnotherList();
contains six strings, and I checked to make sure they weren't null... After
myList1 contained only four strings. Why is that?

Answer Source

Concat returns a new sequence without modifying the original list. Try myList1.AddRange(myList2).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download