i was reviewing a piece of code of a colleague, and i came across a very familiar pattern of code. basically he had a list of employees where he wanted to “loop” over and exclude any employees with age over 30. so his first attempt was the most common one: he used a foreach loop to remove all employees with age > 30. the code looked like the following
foreach (Employee empl in lst)
{
if (empl.age > 30)
lst.Remove(empl);
}
now clearly this will compile but blow up at runtime since it is trying to modify a collection while enumerating it! the second attempt was to create a new list and add all employees with age > 30 to it…that would have worked but it is completely nonesense to do the days.
the first thing that came into my mind is Predicates. so istead what we can do is to define a method as a predicate as follows:
private static bool isAboveAge(Employee empl)
{
return empl.age > 30 ? true : false;
}
then simple call the FindAll method of the list; as follows:
List newLst = lst.FindAll(isAboveAge);
that’s it; now it works in a much better way.
However, why stop there? the only problem with the above code is that i had to create a method (isAboveAge) just for it to being called by FindAll. so to solve this we can use an anonymous method as follows:
List newLst = lst.FindAll(
delegate(Employee empl)
{
return empl.age > 30 ? true : false;
}
);
very cool! but we can take this one more stop…lambda expressions. using lambda we can now – and finally – shrink our code to this:
List newLst = lst.FindAll(empl => empl.age > 30 ? true : false);
Nice!
” ? true : false” is redundant if returns bool. So the above can be written like this:
List newLst = lst.FindAll(empl => empl.age > 30);
which in my opinion is even better
yep, that is true…thnx