How to use C# List Class

The List class in C# is a fundamental component that represents a collection of objects with a strong type association.

List<T> Class
  1. The parameter T is the type of elements in the list.

C# List Class offers the ability to access individual elements within the list through an index-based approach, facilitating efficient retrieval and manipulation of data. One of the key advantages of using the List class is its ability to store values of a specific type without requiring explicit casting to or from the general object type.

Add elements in List collection

Add Integer values in the List collection
List<int> iList = new List<int>(); iList.Add(2); iList.Add(3); iList.Add(5); iList.Add(7);
Add String values in the List
List<string> colors = new List<string>(); colors.Add("Red"); colors.Add("Blue"); colors.Add("Green");

Count list elements

To count the elements in a C# list, you can use the Count property provided by the List class. This property returns the total number of elements present in the list. Here's an example of how you can count the elements in a C# list:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; int count = numbers.Count; Console.WriteLine("Number of elements in the list: " + count); //Output : 5

In the bove example, we create a List<int> called "numbers" and initialize it with some integer values. The Count property is then used to retrieve the count of elements in the list, which is assigned to the variable "count". Finally, we display the count using the Console.WriteLine method.

Retrieve List elements

To retrieve elements from a C# List, you can use the indexing syntax or iteration. Here are examples of how you can retrieve elements from a List:

Using Indexing:
List<string> colors = new List<string> { "Red", "Green", "Blue", "Yellow" }; // Retrieve a single element by index string firstColor = colors[0]; Console.WriteLine("First Color: " + firstColor); // Retrieve multiple elements by index string secondColor = colors[1]; string thirdColor = colors[2]; Console.WriteLine("Second color: " + secondColor); Console.WriteLine("Third color: " + thirdColor);

In the above example, we create a List<string> called "colors" and initialize it with some fruit names. We retrieve individual elements by their index using square brackets and assign them to variables. We then display the retrieved elements using the Console.WriteLine method.

Using Iteration:
List<string> colors = new List<string> { "Red", "Green", "Blue", "Yellow" }; // Iterate over the list and retrieve each element foreach (string color in colors) { Console.WriteLine("Color: " + color); }

In this example, we use a foreach loop to iterate over the List and retrieve each element. Within the loop, we can perform operations on each element or simply display it using the Console.WriteLine method.

Insert List elements

How to insert item in the List c#?

You can use insert(index,item) method to insert an in the specified index.

colors.Insert(1, "violet");

In the above code the color "violet" inserted in the index position 1.

How to sort a C# List

You can use the sort() method of C# List for ordering items in the List.


How to remove an item from List collection ?

Remove() can use to remove item from List collection.


How to check if an item exist in the List collection ?

You can use List.Contains() methods to check an item exists in the List

if (colors.Contains("Blue")) { MessageBox.Show("Blue color exist in the list"); }

How to copy an Array to a List collection ?

string[] strArr = new string[3]; strArr[0] = "Red"; strArr[1] = "Blue"; strArr[2] = "Green"; //here to copy array to List List<string> arrlist = new List<string>(strArr);

How to Convert List to String in C#

You can convert a C# List to a string use the following method.

string combindedString = string.Join(",", colors);

The output look like "Red,Blue,Green"

You can replace the seperator to any character instead of ","

Convert List to Array in C#

You can convert a C# List to an Array using toArray() method.

string[] arr = colors.ToArray();

How to empty a list in C#?

Finally clear method remove all the items from List collection.

arrlist.Clear ();

List Vs Array

c# list example

Arrays are memory-efficient . Lists are built on top of arrays. Because of this, Lists use more memory to store the same data. Array is useful when you know the data is fixed length , or unlikely to grow much. It is better when you will be doing lots of indexing into it, i.e. you know you will often want the third element, or the fifth, or whatever. On the other hand, if you don't know how many elements you'll have, use List. Also, definitely use a List any time you want to add/remove data, since resizing arrays is expensive.

If you are using foreach then the key difference is as follows:


  1. no object is allocated to manage the iteration
  2. bounds checking is removed

List via a variable known to be List :

  1. the iteration management variable is stack allocated
  2. bounds checking is performed

C# List to string

In C#, the ToString() method is used to obtain a string representation of an object. However, when it comes to List<T> in C#, calling ToString() on a list will not give you a meaningful representation of its contents. By default, List<T> inherits the ToString() implementation from the Object class, which returns the fully qualified name of the list's type.

If you want to get a string representation of the elements in a List<T>, you can use the string.Join() method to concatenate the elements into a single string with a specified delimiter.

List<int> numbers = new List<int>() { 100, 200, 300, 400, 500 }; string numbersString = string.Join(", ", numbers);

How to get duplicate items from a list using LINQ

List<String> duplicates = lst.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList();

The GroupBy keyword groups the elements that are the same together, and the Where keyword filters out those that only appear once, leaving you with only the duplicates .

The following C# program shows the implementation of the above functionalities in List collection.

using System; using System.Collections.Generic; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { List <string> colors = new List <string> (); //add items in a List collection colors.Add("Red"); colors.Add("Blue"); colors.Add("Green"); //insert an item in the list colors.Insert(1, "violet"); //retrieve items using foreach loop foreach (string color in colors) { MessageBox.Show(color); } //remove an item from list colors.Remove("violet"); //retrieve items using for loop for (int i = 0; i < colors.Count; i++) { MessageBox.Show(colors[i]); } if (colors.Contains("Blue")) { MessageBox.Show("Blue color exist in the list"); } else { MessageBox.Show("Not exist"); } //copy array to list string[] strArr = new string[3]; strArr[0] = "Red"; strArr[1] = "Blue"; strArr[2] = "Green"; List <string> arrlist = new List <string> (strArr); foreach (string str in strArr) { MessageBox.Show(str); } //call clear method arrlist.Clear (); MessageBox.Show(arrlist.Count.ToString ()); } } }

Last Updated: 20-Jun-2023