13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Equality operations363A.4 Element operationsThis is another selection of query operators that are grouped <strong>in</strong> pairs (see table A.4).This time, the pairs all work the same way. There’s a simple version that picks a s<strong>in</strong>gleelement if it can or throws an exception if the specified element doesn’t exist, and aversion with OrDefault at the end of the name. The OrDefault version is exactly thesame except that it returns the default value for the result type <strong>in</strong>stead of throw<strong>in</strong>g anexception if it can’t f<strong>in</strong>d the element you’ve asked for. All of these operators useimmediate execution.The operator names are easily understood: First and Last return the first andlast elements of the sequence respectively (only default<strong>in</strong>g if there are no elements),S<strong>in</strong>gle returns the only element <strong>in</strong> a sequence (default<strong>in</strong>g if there isn’t exactly oneelement), and ElementAt returns a specific element by <strong>in</strong>dex (the fifth element, forexample). In addition, there’s an overload for all of the operators other thanElementAt to filter the sequence first—for example, First can return the first elementthat matches a given condition.Table A.4S<strong>in</strong>gle element selection examplesExpressionResultwords.ElementAt(2)words.ElementAtOrDefault(10)words.First()words.First(word => word.Length==3)words.First(word => word.Length==10)words.FirstOrDefault(word => word.Length==10)words.Last()words.S<strong>in</strong>gle()words.S<strong>in</strong>gleOrDefault()words.S<strong>in</strong>gle(word => word.Length==5)words.S<strong>in</strong>gle(word => word.Length==10)"two"null"zero""one"Exception: No match<strong>in</strong>g elementsnull"four"Exception: More than one elementnull"three"Exception: No match<strong>in</strong>g elementsA.5 Equality operationsThere’s only one equality operation: SequenceEqual (see table A.5). This just comparestwo sequences for element-by-element equality, <strong>in</strong>clud<strong>in</strong>g order. For <strong>in</strong>stance,the sequence 0, 1, 2, 3, 4 is not equal to 4, 3, 2, 1, 0. An overload allows a specificIEqualityComparer to be used when compar<strong>in</strong>g elements. The return value is justa Boolean, and is computed with immediate execution.Licensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!