combine two lists in csharp

To combine two lists in C#, you have several options. One of the simplest ways is to use the List.AddRange() method, which adds all the elements of one list to another. Here's an example:

main.cs
List<int> list1 = new List<int>() {1, 2, 3};
List<int> list2 = new List<int>() {4, 5, 6};
list1.AddRange(list2);
113 chars
4 lines

This will add all the elements from list2 to list1, resulting in list1 containing {1, 2, 3, 4, 5, 6}.

Another way to combine two lists is to use the List.Concat() method, which returns a new list that contains all the elements of two lists. Here's an example:

main.cs
List<int> list1 = new List<int>() {1, 2, 3};
List<int> list2 = new List<int>() {4, 5, 6};
List<int> combinedList = list1.Concat(list2).ToList();
145 chars
4 lines

This creates a new list called combinedList, which contains all the elements of list1 followed by all the elements of list2. The ToList() method is called at the end to convert the IEnumerable<int> returned by Concat() to a List<int>.

There are many other ways to combine two lists in C#, but these two methods should cover most use cases.

gistlibby LogSnag