I just found that Arrays, Lists, Collections all have these Find, FindAll, etc... functions that use the Predicate syntax. I guess I've noticed them a few times but never actually tried to use them. Check this out.
static void Main(string[] args)
{
// List of Integers
int[] intArray = new int[] { 1, 5, 10, 2, 15, 100, 20, 30 };
int[] intFilter;
// Get all the integers that are less than five [using inline predicate delage]
intFilter = Array.FindAll<int>(intArray, delegate(int testInt) { return testInt < 5; });
DisplayIntList(intFilter);
// If I reused it a lot I can turn it into a function
intFilter = Array.FindAll<int>(intArray, LessThanTen);
DisplayIntList(intFilter);
// If I wanted to pass in the limit I'd have to create a Predicate
intFilter = Array.FindAll<int>(intArray, LessThan(50));
DisplayIntList(intFilter);
}
static bool LessThanTen(int testInt)
{
return testInt < 10;
}
static Predicate<int> LessThan(int limit)
{
return delegate(int testInt) { return testInt < limit; };
}
static void DisplayIntList(int[] intFilter)
{
foreach (int testInt in intFilter) { Console.WriteLine(testInt); } Console.WriteLine();
}