C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Lambda: A lambda expression is a compact syntax form of an anonymous delegate method.
Tip: You can use the delegate keyword with an optional parameter list and a method body instead of a lambda expression.
Info: Usually, lambda expressions are best kept simple to preserve code clarity. For complex methods, using a full declaration is simpler.
C# program that uses RemoveAll method
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(2);
list.Add(4);
list.Add(5);
// Remove all list items with value of 2.
// The lambda expression is the Predicate.
list.RemoveAll(item => item == 2);
// Display results.
foreach (int i in list)
{
Console.WriteLine(i);
}
}
}
Output
1
4
5
Count: The return int is the count of items removed—so if 2 items are removed, the return value is 2.
Nothing removed: If no elements were removed, RemoveAll will return 0. We can check for 0 to see if the list remained unchanged.
Join: This example displays the List contents by calling the string.Join method, which supports a List argument.
JoinC# program that uses RemoveAll return value
using System;
using System.Collections.Generic;
class Program
{
static bool IsRemovable(string item)
{
return item.StartsWith("b");
}
static bool IsRemovableNothingMatches(string item)
{
return item == "x";
}
static void Main()
{
var items = new List<string> { "bird", "frog", "bat" };
Console.WriteLine("ITEMS: {0}", string.Join(",", items));
// Remove 2 items, the result value is 2.
var result = items.RemoveAll(IsRemovable);
Console.WriteLine("COUNT OF ITEM REMOVED: {0}", result);
Console.WriteLine("ITEMS: {0}", string.Join(",", items));
// Nothing is removed with this call.
var result2 = items.RemoveAll(IsRemovableNothingMatches);
// The result is 0.
Console.WriteLine("COUNT, NOTHING REMOVED: {0}", result2);
}
}
Output
ITEMS: bird,frog,bat
COUNT OF ITEM REMOVED: 2
ITEMS: frog
COUNT, NOTHING REMOVED: 0
Tip: The simplest method—the one that is the easiest to read—is usually the best choice.