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. 

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

The following code snippet adds items to the list.

  1. AuthorList.Add("Mahesh Chand");    
  2. AuthorList.Add("Praveen Kumar");    
  3. AuthorList.Add("Raj Kumar");    
  4. AuthorList.Add("Nipun Tomar");    
  5. 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.

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

The following code snippet creates a list of integer type.

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

The following code snippet adds items to the dictionary.

  1. AgeList.Add(35);    
  2. AgeList.Add(25);    
  3. AgeList.Add(29);    
  4. AgeList.Add(21);    
  5. 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.

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

The following code snippet adds items to the list.

  1. PriceList.Add(3.25f);    
  2. PriceList.Add(2.76f);    
  3. PriceList.Add(1.15f);    

Download Free book: Programming List with C# 

Here is a detailed article: Working with C# List 


Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.