C# | Removing the specified element from the List
Last Updated :
01 Feb, 2019
List.Remove(T) Method is used to remove the first occurrence of a specific object from the List.
Properties of List:
- It is different from the arrays. A list can be resized dynamically but arrays cannot.
- List class can accept null as a valid value for reference types and it also allows duplicate elements.
- If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
Syntax:
public bool Remove (T item);
Parameter:
item: Specified object which is to be remove from the List.
Return Type: This method returns True if item is successfully removed. Otherwise it returns False.
Note: This method returns False if item was not found in the List.
Below programs illustrate how to remove the specified element from the List:
Example 1:
using System;
using System.Collections.Generic;
class Geeks {
public static void Main(String[] args)
{
List< int > firstlist = new List< int >();
firstlist.Add(1);
firstlist.Add(2);
firstlist.Add(3);
firstlist.Add(4);
Console.WriteLine( "Before Removing" );
foreach ( int element in firstlist)
{
Console.WriteLine(element);
}
Console.WriteLine( "After Removing" );
firstlist.Remove(2);
foreach ( int element in firstlist)
{
Console.WriteLine(element);
}
}
}
|
Output:
Before Removing
1
2
3
4
After Removing
1
3
4
Example 2:
using System;
using System.Collections.Generic;
class Geeks {
public static void Main(String[] args)
{
List< int > firstlist = new List< int >();
firstlist.Add(1);
firstlist.Add(2);
firstlist.Add(3);
firstlist.Add(4);
firstlist.Add(2);
firstlist.Add(4);
Console.WriteLine( "Before Removing" );
foreach ( int element in firstlist)
{
Console.WriteLine(element);
}
Console.WriteLine( "After Removing" );
firstlist.Remove(2);
foreach ( int element in firstlist)
{
Console.WriteLine(element);
}
}
}
|
Output:
Before Removing
1
2
3
4
2
4
After Removing
1
3
4
2
4
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...