C# List Remove

Description

List Remove removes the first occurrence of a specific object from the List .

Syntax

List.Remove has the following syntax.


public bool Remove(
  T item
)

Parameters

List.Remove has the following parameters.

  • item - The object to remove from the List . The value can be null for reference types.

Returns

List.Remove method returns true if item is successfully removed; otherwise, false. This method also returns false if item was not found in the List.

Example

The following code shows different ways to remove elements from a List.


using System;//from  w  w  w .ja v a2s. c om
using System.Collections;
using System.Collections.Generic;

class Sample
{
    public static void Main()
    {
        //Create a List of Strings
        //String-typed list
        List<string> words = new List<string>();  

        words.Add("A");
        words.Add("B");
        words.Add("C");
        words.Add("D");
        words.Add("E");
        words.Add("F");

        words.Remove("A");
        words.RemoveAt(3);  // Remove the 4th element 
        words.RemoveRange (0, 2); // Remove first 2 elements

        // Remove all strings starting in 'n':
        words.RemoveAll(s => s.StartsWith("n"));


    }
}




















Home »
  C# Tutorial »
    System.Collections.Generic »




HashSet
LinkedList
LinkedListNode
List
Queue
SortedSet
Stack