Those who prefer reading this site through RSS now can also subscribe for updates to .NET Tips & Tricks Community.
Let's review the following code which works with generic collection:
List<String> urls = new List<String>(); //represents a bunch of urls
...
//Remove all urls that don't start with "http://"
for (int i = urls.Count - 1; i >= 0; i--)
{
if (!urls[i].StartsWith("http://", StringComparison.OrdinalIgnoreCase))
urls.RemoveAt(i);
}
This works well but we can do a little better using Predicate (Predicate is essentially a delegate that allows us to filter based on a certain criteria). First, we have to define the method to be the predicate to validate that an url don't starts with an "http://". This would be:
bool IsNonHttp(string url)
return !url.StartsWith("http://", StringComparison.OrdinalIgnoreCase);
Which is essentially the same as the statement we had above. Separating it into a separate method has a few advantages, practically the ability to reuse the same logic for other uses. Now once we have this predicate removing all urls that don't start with an "http://" would be:
urls.RemoveAll(IsNonHttp);
You can also write the whole thing in one line if you so choose by using an anonymous delegate this way:
urls.RemoveAll(delegate(string url) {
});
Other methods of List<T> which take a Predicate: