CodeBlanks Logo Icon CodeBlanks

List<T> methods

C# course · Beginner · Lesson 66/116

Learn to manage List<T> with Remove, Contains and Count.

List<T> methods

The List<T> collection offers several useful methods to manage items. Remove(value) deletes the first item equal to the given value; Contains(value) checks whether the item exists and returns a bool.

The Count property gives the number of items; if Remove succeeds, this number drops by one. Example: nums.Remove(10); removes the value 10 from the list.

RemoveAt and indexer

RemoveAt(index) deletes the item at a specific index; it is useful when you want to delete by position rather than value. nums.RemoveAt(0) removes the first item.

You can access items in the list with the indexer: nums[0] gives the first item. As with arrays, indices start at 0; an invalid index raises ArgumentOutOfRangeException.

Exercise Remove an item and count

Start with List<int> nums = new List<int>() { 5, 10, 15 };. Remove the value 10 with nums.Remove(10). Then print nums.Count with Console.WriteLine.

Show example solution
Remove 10 with nums.Remove(10);, then print the count with Console.WriteLine(nums.Count);.
Example solution:
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> nums = new List<int>() { 5, 10, 15 };
        // Remove 10 and print the count
        nums.Remove(10);
        Console.WriteLine(nums.Count);
    }
}

Test yourself

  1. Remove call

    List<int> nums = new List<int>() { 5, 10, 15 };
    ____
    Console.WriteLine(nums.Count);
    Show answer
    List<int> nums = new List<int>() { 5, 10, 15 };
    nums.Remove(10);
    Console.WriteLine(nums.Count);
  2. What does Contains print?

    List<string> names = new List<string>() { "Ayşe", "Alex" };
    bool has = names.Contains("Ayşe");
    Console.WriteLine(has);
    • false
    • 0
    • true
    • Ayşe
    Show answer

    true — Correct. "Ayşe" is in the list; Contains returns true.

  3. Match each method to its meaning

    nums.Remove(5)
    Removes by value
    nums.RemoveAt(0)
    Removes by index
    nums.Contains(5)
    Checks existence
    nums.Count
    Item count

All lessons in Beginner