Prev | Current Page 661 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

Normally you want to do as much processing as
possible in SQL, but when there are transformations that require ???local??? code, you
sometimes have to force LINQ to use the appropriate Enumerable extension methods.
// Key is first character of word
words.ToLookup(word => word[0])
Lookup contents:
'z': "zero"
'o': "one"
't': "two", "three"
'f': "four"
words.ToDictionary(word => word[0]) Exception: Can only have one entry per key, so
fails on 't'
Table A.3 Conversion examples (continued)
Expression Result
363 Equality operations
A.4 Element operations
This is another selection of query operators that are grouped in pairs (see table A.4).
This time, the pairs all work the same way. There??™s a simple version that picks a single
element if it can or throws an exception if the specified element doesn??™t exist, and a
version with OrDefault at the end of the name. The OrDefault version is exactly the
same except that it returns the default value for the result type instead of throwing an
exception if it can??™t find the element you??™ve asked for. All of these operators use
immediate execution.
The operator names are easily understood: First and Last return the first and
last elements of the sequence respectively (only defaulting if there are no elements),
Single returns the only element in a sequence (defaulting if there isn??™t exactly one
element), and ElementAt returns a specific element by index (the fifth element, for
example).


Pages:
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673