The
ConvertAll()
method introduces yet another application of generic delegates. In this case, the
ConvertAll()
method accepts a
Converter<T, U>
delegate as one of its parameters. The
T
parameter
is used as the source type you are converting from and corresponds to the
T
that is being managed by
the
List<T>
collection. The
U
type parameter corresponds to the type that you are coverting to. For this
example, a delegate is provided that converts from
Customer
objects to strings. It takes each incoming
Customer
and creates a string that contains the
Customer
name with a series of asterisks appended that
are derived from the customer's rating. So, when you run this example, it yields a collection of customer
names that appear as follows:
Happy Gillmore ****
Billy Madison ***
Bobby Boucher ***
Barry Egan ****
Longfellow Deeds **
After converting the names, you use the
CopyTo()
method to make a deep copy of the new list of
names. Whenever you retrieve a collection of items, you should pay attention to whether that collection
contains a shallow or a deep copy. If the copy is shallow, any modifications you make to the returned list
will also result in changes to the original collection. Obviously, plenty of scenarios exist where this may
not be the desired result. In the example, you prove that the copy is deep by modifying the returned col-
lection, setting the value of the first item in the
deepNameCopy
array to "CHANGED NAME". Now, to
confirm that your change didn't impact the original source collection, you dump the contents of both
lists. The resulting output is as follows:
CHANGED NAME
Billy Madison ***
Bobby Boucher ***
Barry Egan ****
Longfellow Deeds **
Happy Gillmore ****
Billy Madison ***
Bobby Boucher ***
Barry Egan ****
Longfellow Deeds **
One more method,
ForEach()
, can be used to operate on the items in a collection. This method lever-
ages the
Action<T>
delegate to specify an action that is to be performed on each item. The
Action<T>
delegate is a simple function that takes just a single parameter and, unlike most of the other delegates
you've looked at, returns no value. Instead, this delegate simply defines a function that will operate -- in
place -- on the supplied item. For the example, your
Action<T>
delegate just converts the name of each
Customer
to uppercase.
Sorting Items
The
List<T>
class provides two methods that can be used to sort the contents of the collection. The first
of these two, the
Sort()
method, includes a set of overloaded versions that support varying approaches
to sorting this collection. The second method,
Reverse()
, allows you to invert the order of the collec-
tion's items. The following example demonstrates both of these methods:
173
BCL Generics
11_559885 ch08.qxd 9/8/05 11:05 PM Page 173