Remove all elements of a List that match the conditions defined by the predicate in C#


To remove all elements from a list that match the conditions defined by the predicate, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i){
      return (i == 500);
   }
   public static void Main(String[] args){
      List<int> list = new List<int>();
      list.Add(100);
      list.Add(500);
      list.Add(300);
      list.Add(400);
      list.Add(500);
      list.Add(600);
      list.Add(500);
      Console.WriteLine("List elements...");
      foreach (int i in list){
         Console.WriteLine(i);
      }
      Console.WriteLine(" ");
      list.RemoveAll(demo);
      Console.WriteLine("List after removing elements 500...");
      foreach (int i in list){
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

List elements...
100
500
300
400
500
600
500

List after removing elements 500...
100
300
400
600

Example

Let us see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i){
      return ((i % 10) == 0);
   }
   public static void Main(String[] args){
      List<int> list = new List<int>();
      list.Add(100);
      list.Add(295);
      list.Add(355);
      list.Add(450);
      list.Add(550);
      Console.WriteLine("List elements...");
      foreach (int i in list){
         Console.WriteLine(i);
      }
      Console.WriteLine(" ");
      list.RemoveAll(demo);
      Console.WriteLine("List after removing elements...");
      foreach (int i in list){
         Console.WriteLine(i);
      }
   }
}

Output

This will produce the following output −

List elements...
100
295
355
450
550

List after removing elements...
295
355

Updated on: 05-Dec-2019

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements