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.cs113 chars4 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.cs145 chars4 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