Using the ConvertAll function with a converter delegate is the easiest way to convert a list of generic objects into specific types. As you might have inferred from its name, a converter delegate is yet another incarnation of anonymous delegates, but one that performs the conversion of each item in a list from a generic object to a specific class.
To see ConvertAll in action, let’s convert a list of DateTime values to a list of other types. First let’s build up a quick List
Predicates.aspx.cs (excerpt)
List
for (DateTime d = DateTime.Now;
d < DateTime.Now.AddMonths(10);
d.AddDays(2)
) { dates.Add(d); }
Now we’ll call dates.ConvertAll with a few different converter delegates to show how easy this approach to converting objects is:
Predicates.aspx.cs (excerpt)
// Convert date list to short date (string) list
List
delegate(DateTime value)
{ return value.ToShortDateString(); }
);
// Convert date list to day of year (int) list
List
delegate(DateTime value)
{ return value.DayOfYear; }
);
// Convert date list to daylight savings time (bool) list
List
delegate(DateTime value)
{ return value.IsDaylightSavingTime(); }
);
Note that we’re taking advantage of type inference to simplify the syntax a little. You can define the converter source and destination types explicitly if you want, like this:
Predicates.aspx.cs (excerpt)
List
(new Converter
(
delegate(DateTime d) { return d.ToShortDateString(); }
)
);
However, as the compiler can see what you’re converting from and to, it will infer those types for you.