Monday, September 04, 2006

Using the new delegate Syste.Predicate

Here's a small case when the new C# 2.0 feature, Predicate<T> may be useful:

Consider an array of file paths retrieved from disk:
string[] s = new string[4] { @"C:\a.jpg", @"C:\b.txt", "c.bmp", "d.swf" };

We can find all the image files (i.e those that have a certain extension) by doing this:

Predicate<string> p = new Predicate<string>(CheckIfImageFile);
string[] newS = Array.FindAll<string>(s, p);

Where CheckIfImageFile is defined here:

static bool CheckIfImageFile(string fullFilePath)
{
string commonImageExtensions = "*.png;*.jpg;*.gif;*.bmp";
if (commonImageExtensions.IndexOf(Path.GetExtension(fullFilePath)) > 0) return true;

return false;
}

No comments: