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
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
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
Nice!
" ? true : false" is redundant if returns bool. So the above can be written like this:
ReplyDeleteList newLst = lst.FindAll(empl => empl.age > 30);
which in my opinion is even better
yep, that is true...thnx
ReplyDelete