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.

368 APPENDIX LINQ standard query operatorsTable A.11Quantifier examplesExpressionwords.All(word => word.Length > 3)words.All(word => word.Length > 2)words.Any()words.Any(word => word.Length == 6)words.Any(word => word.Length == 5)words.Conta<strong>in</strong>s("FOUR")words.Conta<strong>in</strong>s("FOUR",Str<strong>in</strong>gComparer.Ord<strong>in</strong>alIgnoreCase)Resultfalse ("one" and "two" have exactly threeletters)Truetrue (the sequence is not empty)false (no six-letter words)true ("three" satisfies the condition)FalseTrueA.12 Filter<strong>in</strong>gThe two filter<strong>in</strong>g operators are OfType and Where. For details and examples of theOfType operator, see the conversion operators section (A.3). The Where operator (seetable A.12) has overloads so that the filter can take account of the element’s <strong>in</strong>dex. It’sunusual to require the <strong>in</strong>dex, and the where clause <strong>in</strong> query expressions doesn’t usethis overload. Where always uses deferred execution.Table A.12Filter<strong>in</strong>g examplesExpressionwords.Where(word => word.Length > 3)words.Where((word, <strong>in</strong>dex) =><strong>in</strong>dex < word.Length)Result"zero", "three", "four""zero", // length=4, <strong>in</strong>dex=0"one", // length=3, <strong>in</strong>dex=1"two", // length=3, <strong>in</strong>dex=2"three", // length=5, <strong>in</strong>dex=3// Not "four", length=4, <strong>in</strong>dex=4A.13 Set-based operationsIt’s natural to be able to consider two sequences as sets of elements. The four setbasedoperators all have two overloads, one us<strong>in</strong>g the default equality comparison forthe element type, and one where the comparison is specified <strong>in</strong> an extra parameter.All of them use deferred execution.The Dist<strong>in</strong>ct operator is the simplest—it acts on a s<strong>in</strong>gle sequence, and just returnsa new sequence of all the dist<strong>in</strong>ct elements, discard<strong>in</strong>g duplicates. The other operatorsalso make sure they only return dist<strong>in</strong>ct values, but they act on two sequences:■■■Intersect returns elements that appear <strong>in</strong> both sequences.Union returns the elements that are <strong>in</strong> either sequence.Except returns the elements that are <strong>in</strong> the first sequence but not <strong>in</strong> the second.(Elements that are <strong>in</strong> the second sequence but not the first are not returned.)Licensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!