Member-only story
Hi everyone, welcome back. In this example, we will be going over how to add a collection into a list in C#. Lists can be used to store a collection of data, similar to that of an array. The difference being that the lists provide more functionality compared to that of an array, which leaves it as a great option when wanting to modify a collection of data. With this introduction out of the way, let’s get into it.
Creating And Populating List
Let’s start by creating a list. Before we can create the list, we need to make sure that we have our list import, which is included within the System.Collections.Generic package:
using System.Collections.Generic;
Now, we can create and populate our list:
List<string> myList = new List<string>()
{
"One",
"Two",
"Three"
};
We have now successfully created and populated our list.
Adding a Collection Into The List
Now, let’s try to add a collection of data into our list. We can do this by using the built in AddRange() function that is provided. We will create a separate collection and attempt to add it into our list. Let’s see an example: