Ryan Farber's WebLog

Find and FindAll in .NET 2.0 collections

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();
}

Published Friday, July 28, 2006 8:25 AM by rfarber

Comments

 

SpoonsJTD said:

Took .Net 2.0 to get one baby step toward what we had with C++'s STL. Even in .NET, even with C#, I'd prefer to see a separation of collection from algorithm. For people who really really want the algorithms on their collections, wait for extension methods in c# 3.0.
July 28, 2006 12:15 PM
 

.NET a 2.860 m de altura said:

Hace rato que no hab&#237;a escrito sobre alg&#250;n truco ch&#233;vere de C#, pues bueno, me acabo de encontrar con...
August 2, 2006 11:14 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker