C# List: Exploring the Power of C# Lists

Download Sample Source Code

C# List is a collection of strongly typed objects. It is a generic class, which means that it can be used for storing objects of any type.

The C# List class is located in the System.Collections.Generic namespace. We are going to share detailed information with code examples today. Also you can create a free account on FreeASPHosting.net and start practicing C# Lists live by uploading your entire website!

KEY TAKEAWAYS:

  1. C# List is a generic class in the System.Collections.Generic namespace that allows storing objects of any type. Unlike arrays, Lists in C# are dynamic and can resize themselves as needed.
  2. Creating and initializing a List in C# is simple. The necessary namespace to import is System.Collections.Generic and a List can be created by specifying the type in angle brackets, such as List<string>. Values can be initialized using curly braces.
  3. Items can be added to a List in C# using the Add method, and items can be inserted at a specific position using the Insert method.
  4. To iterate through a List in C#, various looping structures like for loop and foreach loop can be used. The List elements can be accessed and processed accordingly.
  5. Operations like removing an item, clearing all elements, checking if an item exists, sorting, reversing, and finding an item in a C# List can be performed using methods like Remove, Clear, Contains, Sort, Reverse, and Find.

What Is List In C#

In C#, the List<T> class represents a strongly typed list of objects. Unlike arrays, Lists in C# are dynamic, meaning they can automatically resize themselves as needed. The capacity of a C# List is the number of elements it can hold. As elements get added to a List, its capacity is automatically increased as required.

Creating and Initializing a List C#

Let’s dive headfirst into Lists C#, how to make a List in C# with code examples, and much more!

Create List in C#

Making a List in C# is simple and straightforward. Firstly, you'll need to import the necessary namespace, which is the System.Collections.Generic namespace. Here's a basic example for you to show how to create a List C#:

using System.Collections.Generic;

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

In this example, a C# List of strings is created. However, List<T> is a generic class, and T can be replaced with any valid data type.

C# Initialize List with Values

Once you've created a C# List, you might want to initialize a List C# with some values. Here's how you do it:

List<int> intList = new List<int> {1, 2, 3, 4, 5};

This C# List of integers is initialized with these values 1, 2, 3, 4, and 5.

Instantiating a C# string list with values is done in a similar way. Here's how:

List<string> stringList = new List<string> {"apple", "banana", "cherry"};

This string list c# is instantiated with the values "apple", "banana", and "cherry".

Following, you will see a complete C# console code that uses the above C# Lists.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> intList = new List<int> { 1, 2, 3, 4, 5 };
        List<string> stringList = new List<string> { "apple", "banana", "cherry" };

        Console.WriteLine("Integers:");
		
        foreach (int num in intList)
        {
            Console.WriteLine(num);
        }

        Console.WriteLine("\nStrings:");
		
        foreach (string str in stringList)
        {
            Console.WriteLine(str);
        }
    }
}

C# List

Using List C#

How To Add Items To List In C#

Items can be added to a C# List using the Add method. Here's an example:

List<string> stringList = new List<string>();
stringList.Add("apple");
stringList.Add("banana");

In this example, "apple" and "banana" are added to the List C#.

C# List Add At Index

You can insert a list element at a specific position in a C# List using the Insert method. Look at this example:

List<int> intList = new List<int> {1, 2, 3, 4, 5};
intList.Insert(2, 99);

In this example, the number 99 is inserted at the second index (third position) of the C# List.

C# Iterate Through a List

To loop through a list element in a C# List, you can use a for loop, a foreach loop, or other looping structures. You already saw of full C# console example in the “C# Initialize List with Values” section, look at this using a foreach loop:

List<string> stringList = new List<string> {"apple", "banana", "cherry"};

foreach (string item in stringList)
{
    Console.WriteLine(item);
}

This code will print each item in the C# List to the console.

C# Remove List Item

You can remove an item from a C# List using the Remove method. Here's an example:

List<string> stringList = new List<string> {"apple", "banana", "cherry"};
stringList.Remove("banana");

Here we are removing "banana" from the C# List.

C# List Clear

To clear all list elements from a C# List, you can use the Clear method. Here's an example:


List<int> intList = new List<int> {1, 2, 3, 4, 5};
intList.Clear();

After executing this code, intList will be empty.

C# Check If a List Contains An Item

We can also check if an item exists in a C# List using the C# Contains method. Here's an example:

using System.Collections.Generic;

List<string> stringList = new List<string> {"apple", "banana", "cherry"};
bool hasApple = stringList.Contains("apple");

In this example, hasApple will be true if "apple" is in the List and false otherwise.

Sort List In C#

You can sort a C# List using the Sort method. Here's an example:

List<int> intList = new List<int> {5, 2, 3, 1, 4};
intList.Sort();

After executing this code, intList will be {1, 2, 3, 4, 5}.

C# List Reverse

C# List can be reversed using the Reverse method. Here's an example:

using System.Collections.Generic;

List<int> intList = new List<int> {1, 2, 3, 4, 5};
intList.Reverse();

After executing this code, intList will be {5, 4, 3, 2, 1}.

C# List Find Item

Finding an item in a C# List can be done using the C# Find method. We have an example for you here:

List<int> intList = new List<int> {5, 2, 3, 1, 4};
int firstOddNumber = intList.Find(x => x % 2 != 0);

Here, firstOddNumber will be 5, as it's the first odd number in the List.

C# Advanced Topics List

Go forth and learn some advanced operations with Lists C#:

C# Find Item In List Linq

You can select items from a C# List using LINQ. Here's an example using C# Linq Where In List.

using System.Collections.Generic;
using System.Linq;

List<int> intList = new List<int> {5, 2, 3, 1, 4};
List<int> evenNumbers = intList.Where(x => x % 2 == 0).ToList();

In this example, evenNumbers will be a new List containing only the even numbers from intList. Let’s look at the complete working example!

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<int> intList = new List<int> { 5, 2, 3, 1, 4, 6, 59, 88, 112, 225, 226, 9, 96 };
        List<int> evenNumbers = intList.Where(x => x % 2 == 0).ToList();

        // Printing the even numbers in intList
        Console.WriteLine("Even numbers in intList:");
        foreach (int number in evenNumbers)
        {
            Console.WriteLine(number);
	  }
    }
}

It will produce the following output values on the console!

C# List

C# LINQ Map List To Another List

If we want to map one C# List to another List, we can do this using LINQ.

Example:

List<int> intList = new List<int> {1, 2, 3, 4, 5};
List<int> squaredNumbers = intList.Select(x => x * x).ToList();

In this example, squaredNumbers will be a new C# List containing the squares of the numbers in intList. We are using LINQ's Select method with a lambda expression x => x * x to map each number in the intList to its square. The result is stored in a new list called squaredNumbers.

C# List Import

You can import items from one C# List to another List using the AddRange method in C#. Look at this code:

List<int> intList1 = new List<int> {1, 2, 3, 4, 5};
List<int> intList2 = new List<int> {6, 7, 8, 9, 10};
intList1.AddRange(intList2);

Here, the list elements from intList2 are added to the end of intList1.

C# List To Array

C# List can be converted to an Array using the ToArray method. Here's an example:

List<int> intList = new List<int> {1, 2, 3, 4, 5};
int[] intArray = intList.ToArray();

intArray will be an array containing the same items as intList.

C# Join Two Lists

You can join two C# Lists together using the Concat method. Here's an example:

List<int> intList1 = new List<int> {1, 2, 3, 4, 5};
List<int> intList2 = new List<int> {6, 7, 8, 9, 10};
List<int> combinedList = intList1.Concat(intList2).ToList();

In this example, combinedList will be a new List containing the list element from both intList1 and intList2.

Sort List In C#

C# List can be sorted by property using LINQ.

List<string> stringList = new List<string> {"apple", "banana", "graps"};
List<string> sortedList = stringList.OrderBy(s => s.Length).ToList();

sortedList will be a new List containing the items from stringList, sorted by their length.

C# Length Of List

If we want to get the length or number of elements in a List<T>, we can use the Count property.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

// Get the length of the list
int length = numbers.Count;

Here we are using the Count property to fetch the number of elements in the list and storing it in the length variable.

C# List Extension Method

Extension methods let us add new methods to existing types without modifying them. Here's an example of an extension method for the List class in C#:

using System.Collections.Generic;

public static class ListExtensions
{
    public static bool IsEmpty<T>(this List<T> list)
    {
        return list.Count == 0;
    }
}

This extension method adds an IsEmpty method to all Lists in C#. We can call it like this:

List<int> intList = new List<int>();
bool isEmpty = intList.IsEmpty();

In this example, isEmpty will be true if intList is empty and false otherwise.

List Of Lists

In C#, a List Of List can be represented using the List<List<T>> class. Following is a detailed example of how you can declare and work with a List Of Lists.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Declare a list of lists
        List<List<int>> listOfLists = new List<List<int>>();

        // Create and add sublists to the main list
        List<int> sublist1 = new List<int> { 1, 2, 3 };
        List<int> sublist2 = new List<int> { 4, 5 };
        List<int> sublist3 = new List<int> { 6, 7, 8 };
        listOfLists.Add(sublist1);
        listOfLists.Add(sublist2);
        listOfLists.Add(sublist3);

        // Access and modify elements in the list of lists
        int element = listOfLists[0][1]; // Access element at index [0][1] (2nd element of sublist1)
        Console.WriteLine("Element at [0][1]: " + element);

        listOfLists[2].Add(9); // Add element 9 to sublist3

        // Print the elements in the list of lists
        Console.WriteLine("Elements in the list of lists:");
        foreach (List<int> sublist in listOfLists)
        {
            foreach (int num in sublist)
            {
                Console.Write(num + " ");
            }
            Console.WriteLine();
        }

        // Wait for user input to exit
        Console.ReadKey();
    }
}

We can access and modify elements in the List of Lists using the indexing notation. For example, listOfLists[0][1] accesses the element at index 1 of sublist1. We can also perform operations on the sublists, such as adding elements to sublist3 using listOfLists[2].Add(9). Look at the output!

C# List

C# List Properties

The List class in C# has several useful properties. Here are a few of them:

  1. Count: Returns the number of C# List elements.
  2. Capacity: Returns or sets the total number of elements the internal data structure can contain without resizing.
  3. Item[index]: Gets or sets the C# List element at the specified index.

C# List Methods

The List class in C# also provides several useful methods. Here are a few examples:

  1. Add(item): Adds an item to the very end of the List.
  2. Remove(item): Removes first occurrence of a specific object from the C# List.
  3. Find(predicate): Finds an item in the List that matches the conditions defined by the specified predicate.
  4. Sort(): Sorts the elements in the entire C# List using the default comparer.

Final Words

Lists in C# are a powerful tool for managing collections of items. They offer much more functionality and flexibility than arrays, including automatic resizing, easy addition and removal of items, and powerful querying capabilities with LINQ.

With List<T>, we can store any type of object, and the type safety of generics ensures that we won't accidentally insert the wrong type of list element into our C# List.

In this article, we've covered how to create and initialize C# Lists, add, insert, remove, and find items, sort, reverse, and perform advanced operations using LINQ. We've also discussed some useful List properties and methods.

Whether you're just getting started with C# or you're an experienced developer, understanding Lists is crucial for effective programming. With the knowledge and examples provided in this article, you're now well-equipped to use Lists in your own C# projects.