How to create a List in C#

Introduction 

A list is a collection of items that can be accessed by index and provides functionality to search, sort and manipulate list items. 

The List<T> class defined in the System.Collections.Generic namespace is a generic class and can store any data types to create a list. Before you use the List class in your code, you must import the System.Collections.Generic namespace using the following line.

using System.Collections.Generic;
 
Creating a List

The List class constructor takes a key data type. The data type can be any .NET data type. 

The following code snippet creates a List of string types. 

List<string> AuthorList = new List<string>();

The following code snippet adds items to the list.  

AuthorList.Add("Mahesh Chand");
AuthorList.Add("Praveen Kumar");
AuthorList.Add("Raj Kumar");
AuthorList.Add("Nipun Tomar");
AuthorList.Add("Dinesh Beniwal");

Alternatively, we can also pass an array of objects to create a List object. The following code snippet creates a List object from an array of strings. 

// Create a List using Range
string[] authors = { "Mike Gold", "Don Box",
                        "Sundar Lal", "Neel Beniwal" };
List<string> authorsRange = new List<string>(authors);

The following code snippet creates a list of integer type. 

List<int> AgeList = new List<int>();

The following code snippet adds items to the dictionary.  

AgeList.Add(35);
AgeList.Add(25);
AgeList.Add(29);
AgeList.Add(21);
AgeList.Add(84);

We can also limit the size of a list. The following code snippet creates a list where the key type is float and the total number of items it can hold is 3.  

List<float> PriceList = new List<float>(3);

The following code snippet adds items to the list.  

PriceList.Add(3.25f);
PriceList.Add(2.76f);
PriceList.Add(1.15f);

Download Free book: Programming List with C#

Up Next
    Ebook Download
    View all
    Learn
    View all