13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Conversion361Cast and OfType convert an untyped sequence <strong>in</strong>to a typed one, either throw<strong>in</strong>gan exception (for Cast) or ignor<strong>in</strong>g (for OfType) elements of the <strong>in</strong>put sequence thataren’t implicitly convertible to the output sequence element type. This may also beused to convert typed sequences <strong>in</strong>to more specifically typed sequences, such as convert<strong>in</strong>gIEnumerable to IEnumerable. The conversions are performed<strong>in</strong> a stream<strong>in</strong>g manner with deferred execution.ToDictionary and ToLookup both take delegates to obta<strong>in</strong> the key for any particularelement; ToDictionary returns a dictionary mapp<strong>in</strong>g the key to the element type,whereas ToLookup returns an appropriately typed ILookup. A lookup is like a dictionarywhere the value associated with a key isn’t one element but a sequence of elements.Lookups are generally used when duplicate keys are expected as part of normal operation,whereas a duplicate key will cause ToDictionary to throw an exception. Morecomplicated overloads of both methods allow a custom IEqualityComparer to beused to compare keys, and a conversion delegate to be applied to each element beforeit is put <strong>in</strong>to the dictionary or lookup.The examples <strong>in</strong> table A.3 use two additional sequences to demonstrate Cast andOfType:object[] allStr<strong>in</strong>gs = {"These", "are", "all", "str<strong>in</strong>gs"};object[] notAllStr<strong>in</strong>gs = {"Number", "at", "the", "end", 5};Table A.3Conversion examplesExpressionallStr<strong>in</strong>gs.Cast()allStr<strong>in</strong>gs.OfType()notAllStr<strong>in</strong>gs.Cast()notAllStr<strong>in</strong>gs.OfType()Result"These", "are", "all", "str<strong>in</strong>gs"(as IEnumerable)"These", "are", "all", "str<strong>in</strong>gs"(as IEnumerable)Exception is thrown while iterat<strong>in</strong>g, at po<strong>in</strong>t of fail<strong>in</strong>gconversion"Number", "at", "the", "end"(as IEnumerable)numbers.ToArray() 0, 1, 2, 3, 4(as <strong>in</strong>t[])numbers.ToList() 0, 1, 2, 3, 4(as List)words.ToDictionary(word =>word.Substr<strong>in</strong>g(0, 2))Dictionary contents:"ze": "zero""on": "one""tw": "two""th": "three""fo": "four"Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!