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
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)The new class provides flexibility in searching elements of the collection.
{
StringFilter sf = new StringFilter(strA);
if (B.Exists(sf.ContainsString)) { /* do something... */ }
if (C.Exists(sf.StartsWithString)) { /* do something... */ }
}
Labels: dotnet, microsoft, programming


0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home