13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Generic collection classes <strong>in</strong> .NET 2.097■Remove all elements <strong>in</strong> the list match<strong>in</strong>g a given predicate (RemoveAll).■ Perform a given action on each element on the list (ForEach). 10We’ve already seen the ConvertAll method <strong>in</strong> list<strong>in</strong>g 3.2, but there are two more delegatetypes that are very important for this extra functionality: Predicate andAction, which have the follow<strong>in</strong>g signatures:public delegate bool Predicate (T obj)public delegate void Action (T obj)A predicate is a way of test<strong>in</strong>g whether a value matches a criterion. For <strong>in</strong>stance, youcould have a predicate that tested for str<strong>in</strong>gs hav<strong>in</strong>g a length greater than 5, or onethat tested whether an <strong>in</strong>teger was even. An action does exactly what you might expectit to—performs an action with the specified value. You might pr<strong>in</strong>t the value to theconsole, add it to another collection—whatever you want.For simple examples, most of the methods listed here are easily achieved with aforeach loop. However, us<strong>in</strong>g a delegate allows the behavior to come from somewhereother than the immediate code <strong>in</strong> the foreach loop. With the improvements todelegates <strong>in</strong> <strong>C#</strong> 2, it can also be a bit simpler than the loop.List<strong>in</strong>g 3.13 shows the last two methods—ForEach and RemoveAll—<strong>in</strong> action. Wetake a list of the <strong>in</strong>tegers from 2 to 100, remove multiples of 2, then multiples of 3, andso forth up to 10, f<strong>in</strong>ally list<strong>in</strong>g the numbers. You may well recognize this as a slightvariation on the “Sieve of Eratosthenes” method of f<strong>in</strong>d<strong>in</strong>g prime numbers. I’ve usedthe streaml<strong>in</strong>ed method of creat<strong>in</strong>g delegates to make the example more realistic.Even though we haven’t covered the syntax yet (you can peep ahead to chapter 5 ifyou want to get the details), it should be fairly obvious what’s go<strong>in</strong>g on here.List<strong>in</strong>g 3.13Pr<strong>in</strong>t<strong>in</strong>g primes us<strong>in</strong>g RemoveAll and ForEach from ListList candidates = new List();for (<strong>in</strong>t i=2; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!