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
OfType : The conversion operator OfType
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
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
ToLookup:ToLookup converts an IEnumerable
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:
Post a Comment