For instance, you
could have a predicate that tested for strings having a length greater than 5, or one
that tested whether an integer was even. An action does exactly what you might expect
it to??”performs an action with the specified value. You might print the value to the
console, add it to another collection??”whatever you want.
For simple examples, most of the methods listed here are easily achieved with a
foreach loop. However, using a delegate allows the behavior to come from somewhere
other than the immediate code in the foreach loop. With the improvements to
delegates in C# 2, it can also be a bit simpler than the loop.
Listing 3.13 shows the last two methods??”ForEach and RemoveAll??”in action. We
take a list of the integers from 2 to 100, remove multiples of 2, then multiples of 3, and
so forth up to 10, finally listing the numbers. You may well recognize this as a slight
variation on the ???Sieve of Eratosthenes??? method of finding prime numbers. I??™ve used
the streamlined method of creating delegates to make the example more realistic.
Even though we haven??™t covered the syntax yet (you can peep ahead to chapter 5 if
you want to get the details), it should be fairly obvious what??™s going on here.
List
candidates = new List();
for (int i=2; i <= 100; i++)
{
candidates.Add(i);
}
for (int factor=2; factor <= 10; factor++)
{
candidates.
Pages:
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211