RemoveAll Demo

CSharp · Console

/Program.cs

using System;
					
using System.Collections.Generic;
using System.Linq;

public class Program
{
	
	// SEE: https://stackoverflow.com/q/10018957/1016343

	//If you have:
	class myClass {
    	public int ID; public string FirstName; public string LastName;
	}


	public static void Main()
	{

		//and assigned some values to results as follows: 
		var results=new List<myClass> {
			new myClass()  { ID=1, FirstName="Bill", LastName="Smith" },
			new myClass()  { ID=2, FirstName="John", LastName="Wilson" },
			new myClass()  { ID=3, FirstName="Doug", LastName="Berg" },
			new myClass()  { ID=4, FirstName="Bill", LastName="Wilson" },
		};
		
		//Then you can define a list of IDs to remove:
		var removeList = new List<int>() { 2, 3 };

		Console.WriteLine("\nBefore:");
		foreach(var x in results) {
			Console.WriteLine(x.FirstName + " " + x.LastName);
		}
		
		//And simply use this to remove them:
		
		results.RemoveAll(r => removeList.Any(a => a==r.ID));
		
		// Usage for removal of single items:
		results.RemoveAll(r => r.ID==4);
		
		Console.WriteLine("\nAfter:");
		foreach(var x in results) {
			Console.WriteLine(x.FirstName + " " + x.LastName);
		}

	}
}
;