Predicates in dotNet
I've come across Predicates in dotNet 2.0. I felt so disgusted with too many foreach loops when looping through list collections. So, here was my problem: I have three string Lists, say, A, B and C. List string A is the reference list; while B and C contain elements found in A. By brute force method (and practically the only way we can do it in dotNet 1.x), we do something like:
foreach (string strA in A)
{
foreach (string strB in B)
{
if (strB.Contains(strB)) { /* do something... */ }
}
foreach (string strC in C)
{
if (strC.StartsWith(strC)) { /* do something... */ }
}
}

In dotNet 2.0, Predicates are provided for the generic features such as the System.Array and System.Collections.Generic.List classes. These classes provide methods like Find, FindAll, FindLast, etc. that use predicates to help developers search for certain elements in collections via delegates rather than looping at each element. Developers get the ability to "walk" an entire data structure, determining whether each item meets a set of criteria, without having to write the boilerplate code to loop through each row manually. In addition, it is more efficient to go.

Okay, back to our example. By employing predicates, I created a new class called StringFilter:
public class StringFilter
{
private string _strReference;
public bool ContainsString(string s)
{
return s.Contains(_strReference);
}
public bool StartsWithString(string s)
{
return s.StartsWith(_strReference, StringComparison.InvariantCultureIgnoreCase);
}
public StringFilter(string strReference)
{
_strReference = strReference;
}
}

Now, rewriting our example using this new class as predicate:

foreach (string strA in A)
{
StringFilter sf = new StringFilter(strA);
if (B.Exists(sf.ContainsString)) { /* do something... */ }
if (C.Exists(sf.StartsWithString)) { /* do something... */ }
}
The new class provides flexibility in searching elements of the collection.

Read the complete post at http://alexrazon.blogspot.com/2006/11/predicates-in-dotnet.html

Published 11-19-2006 5:20 PM by Alexis' Blog