Prev | Current Page 200 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

RemoveAll (delegate(int x)
{ return x>factor && x%factor==0; }
);
}
candidates.ForEach (delegate(int prime)
{ Console.WriteLine(prime); }
);
10 Not to be confused with the foreach statement, which does a similar thing but requires the actual code in
place, rather than being a method with an Action parameter.
Listing 3.13 Printing primes using RemoveAll and ForEach from List
Populates list
of candidate
primes
B
Removes
nonprimes
C
Prints out
remaining
elements
D
98 CHAPTER 3 Parameterized typing with generics
Listing 3.13 starts off by just creating a list of all the integers between 2 and 100 inclusive
B??”nothing spectacular here, although once again I should point out that
there??™s no boxing involved. The delegate used in step C is a Predicate , and
the one used in D is an Action. One point to note is how simple the use of
RemoveAll is. Because you can??™t change the contents of a collection while iterating
over it, the typical ways of removing multiple elements from a list have previously been
as follows:
?–  Iterate using the index in ascending order, decrementing the index variable
whenever you remove an element.
?–  Iterate using the index in descending order to avoid excessive copying.
?–  Create a new list of the elements to remove, and then iterate through the new
list, removing each element in turn from the old list.


Pages:
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212