C# List RemoveAll
Description
List
removes all the elements that
match the conditions defined by the specified predicate.
Syntax
List.RemoveAll
has the following syntax.
public int RemoveAll(
Predicate<T> match
)
Parameters
List.RemoveAll
has the following parameters.
match
- The Predicatedelegate that defines the conditions of the elements to remove.
Returns
List.RemoveAll
method returns The number of elements removed from the List.
Example
The following code shows different ways to remove elements from a List.
using System;//w ww .j a v a 2 s . 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"));
}
}
Example 2
/*ww w . j a va 2 s .c o m*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
class Primes
{
static void Main()
{
List<int> candidates = new List<int>();
for (int i=2; i <= 100; i++)
{
candidates.Add(i);
}
for (int factor=2; factor <= 10; factor++)
{
candidates.RemoveAll (delegate(int x)
{ return x>factor && x%factor==0; }
);
}
candidates.ForEach (delegate(int prime)
{ Console.WriteLine(prime); }
);
}
}
The code above generates the following result.