
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Performing Multiple Operations on a List Using Functors
|
555
return false;
});
}
The first thing you do is make sure the list is sorted so that the best performing
stocks are at the front of the list by calling the
Sort method on List<T>. One of the
overloads of the Sort method is defined to take a
Comparison<T> which is defined like
this:
public delegate int Comparison<T>(T x, T y)
You create the Comparison you need by using the Comparer<T> class passing a double
as the argument and using the default comparison method, while passing the gain/
loss percentage for each stock as it is iterated over by the
Sort function. The stocks
being compared (
rhs, lhs) are reversed to place the best performing stocks at the
front of the list:
return Comparer<double>.Default.Compare(rhs.GainLoss, lhs.GainLoss);
Your comparison tells Sort which object should be placed ahead of the other. This is
a simple callback from
Sort that allows you to control the algorithm to determine
sort order. You wrapped this up in an anonymous method by using the
delegate key-
word and now you have your
Comparison delegate that the Sort function needs.
Now that your list is sorted, you use the
FindAll function from List<T>, which takes
a
Predicate<T> as the parameter. Again you use the delegate keyword to create an
anonymous method ...