February 2, 2008

Anonymous Delegates And Iterators

c# 2.0 Iterators
Using anonymous delegates

This code: (Note how an anonymous method can access local variables!)
...
XXX mainXXX = ...
...
xxxList.RemoveAll(
    delegate(XXX xxx)
    {
        return xxx.Id == mainXXX.Id; 
    }
);
Does the same as this:
List entriesToRemove = new List();
foreach (XXX xxx in xxxList)
{
    if (xxx.Id == mainXXX.Id)
    {
        entriesToRemove.Add(xxx);
    }
}
foreach (XXX xxx in entriesToRemove)
{
    xxxList.Remove(userToRemove);
}

No comments: