January 22, 2007

dotNET - Lists comparisons and Predicates

Here's something I've found very useful but at first found very difficult to understand.
When trying to find certain contents of a list you have a few options open to you.
The first is to enumerate through the list and do a comparison of each value in the list, this is the old way to do things:
foreach (string sf in sourceFiles)
{
if (sf.Contains("DBAccess.js"))
containsDBAccess = true;
}

.NET has provided a better implementation using Predicates.
Predicates are implemented with delegates.
You implement your Predicate with with a Function which takes a single parameter, a string, and returns bool.
e.g.
private static bool FindDBAccess(string s)
{
return s.Contains("DBAccess.js");
}
and use this in the List.Find like so
if (sourceFiles.Find(FindDBAccess) == null)
{........
}

The string 's' passed as a parameter is actually each of the values in the list.
The delegate FindDBAccess is called for each item in the list, and if it returns True for any one of these items we have success. In this case we compare 's' each time with a certain string, "DBAccess.js" in this case.

There is a shorthand way of writing this too, no need for the actual Predicate method:
if (sourceFiles.Find(new Predicate(delegate(string target) { return target.Contains("DBAccess.js"); })) == null)
{
}

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.