Tuesday, February 10, 2009

Using Conversion Types

A very common task is converting data from one form to another.
The new version of .NET has conversion operators ToArray, OfType, Cast, AsEnumerable, ToList, ToDictionary, and ToLookup. We will discuss each one by one:

ToArray : Arrays are fast but not very convenient. It is tedious to write array management code when collections like List make managing data easier.The main reason, dot net framework supprots ToArray because many legacy code and API supprots uses ToArray till now.
OfType : The conversion operator OfType returns an IEnumerable collection of only the types defined by the parameter T. For example, initializing a list of objects where some are integers, you can quickly extract just the integers
var numbers = new object[]{1, "two", null, "3", 4};
foreach(var anInt in numbers.OfType())
Console.WriteLine(anInt);
Cast: To receive an exception if elements of the source type cannot be converted to the target type, use the Cast conversion operator.
AsEnumerable : Many types implement IEnumerable.AsEnumerable Forces an Object That Implements IEnumerable to Use theBehaviors of the IEnumerable Interface.
ToList: The ToList conversion operator forces an immediate query evaluation and stores the results in a List.
ToDictionary:A dictionary is a collection of name and value pairs. ToDictionary converts anIEnumerable object—such as is returned from a LINQ query—into anIDictionary object.
ToLookup:ToLookup converts an IEnumerable to a Lookup type. Lookup is like a dictionary, but where a Dictionary uses a single key value, Lookup maps keys to a collection of values. Lookups have no public constructor and are immutable. You cannot add or remove elements or keys after they are created.

Summary:
Compound type initialization makes it easier to initialize arrays and lists and is an essential capability for initializing anonymous types. Conversion operators take some of the tedium out of converting between convenient types and other types. More important, this chapter demonstrates the classic onion layering of complexity in .NET that makes it possible to do a lot of work with relatively few lines of code.

No comments: