├── LINQTut20 ├── LINQTut20.csproj ├── Extensions.cs ├── Deck.cs ├── Card.cs └── Program.cs ├── LINQTut20.sln └── .gitignore /LINQTut20/LINQTut20.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /LINQTut20/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace LINQTut20 5 | { 6 | public static class Extensions 7 | { 8 | public static void PrintDeck(this IEnumerable cards, string title) 9 | { 10 | Console.WriteLine($"\n\n\n###### {title} ######"); 11 | foreach (Card card in cards) 12 | { 13 | Console.WriteLine(card.Name); 14 | } 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LINQTut20.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32112.339 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LINQTut20", "LINQTut20\LINQTut20.csproj", "{4EA2460A-202B-4099-94BF-C3F215AC74B6}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {4EA2460A-202B-4099-94BF-C3F215AC74B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {4EA2460A-202B-4099-94BF-C3F215AC74B6}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {4EA2460A-202B-4099-94BF-C3F215AC74B6}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {4EA2460A-202B-4099-94BF-C3F215AC74B6}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {2ECF5A87-0E7C-4C4F-AE86-925B00C2DAFB} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /LINQTut20/Deck.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace LINQTut20 6 | { 7 | public class Deck 8 | { 9 | private static Random rnd = new Random(); 10 | public IEnumerable FillDeck() 11 | { 12 | for (int i = 0; i < 52; i++) 13 | { 14 | Card.Suites suite = (Card.Suites)(Math.Floor((decimal)i / 13)); 15 | int val = i % 13 + 2; 16 | yield return (new Card(val, suite)); 17 | } 18 | } 19 | 20 | internal IEnumerable GetSample() 21 | { 22 | yield return FillDeck().Single(x => x.Value == 11 && x.Suite == Card.Suites.CLUBS); 23 | yield return FillDeck().Single(x => x.Value == 9 && x.Suite == Card.Suites.DIAMONDS); 24 | yield return FillDeck().Single(x => x.Value == 4 && x.Suite == Card.Suites.HEARTS); 25 | yield return FillDeck().Single(x => x.Value == 10 && x.Suite == Card.Suites.SPADES); 26 | yield return FillDeck().Single(x => x.Value == 3 && x.Suite == Card.Suites.HEARTS); 27 | yield return FillDeck().Single(x => x.Value == 6 && x.Suite == Card.Suites.HEARTS); 28 | } 29 | 30 | public IEnumerable Shuffle() 31 | { 32 | return FillDeck().OrderBy(x=>rnd.Next()); 33 | } 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /LINQTut20/Card.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Threading.Tasks; 3 | 4 | namespace LINQTut20 5 | { 6 | public class Card 7 | { 8 | public enum Suites 9 | { 10 | HEARTS = 0, 11 | DIAMONDS, 12 | CLUBS, 13 | SPADES 14 | } 15 | 16 | public int Value { get; set; } 17 | public Suites Suite { get; set; } 18 | 19 | public string NamedValue 20 | { 21 | get 22 | { 23 | string name = string.Empty; 24 | switch (Value) 25 | { 26 | case (14): 27 | name = "Ace"; 28 | break; 29 | case (13): 30 | name = "King"; 31 | break; 32 | case (12): 33 | name = "Queen"; 34 | break; 35 | case (11): 36 | name = "Jack"; 37 | break; 38 | default: 39 | name = Value.ToString(); 40 | break; 41 | } 42 | 43 | return name; 44 | } 45 | } 46 | 47 | public string Name 48 | { 49 | get 50 | { 51 | return NamedValue + " of " + Suite.ToString(); 52 | } 53 | } 54 | 55 | public bool IsRed => Suite == Suites.HEARTS || Suite == Suites.DIAMONDS; 56 | 57 | public Card(int Value, Suites Suite) 58 | { 59 | this.Value = Value; 60 | this.Suite = Suite; 61 | } 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # Tye 66 | .tye/ 67 | 68 | # ASP.NET Scaffolding 69 | ScaffoldingReadMe.txt 70 | 71 | # StyleCop 72 | StyleCopReport.xml 73 | 74 | # Files built by Visual Studio 75 | *_i.c 76 | *_p.c 77 | *_h.h 78 | *.ilk 79 | *.meta 80 | *.obj 81 | *.iobj 82 | *.pch 83 | *.pdb 84 | *.ipdb 85 | *.pgc 86 | *.pgd 87 | *.rsp 88 | *.sbr 89 | *.tlb 90 | *.tli 91 | *.tlh 92 | *.tmp 93 | *.tmp_proj 94 | *_wpftmp.csproj 95 | *.log 96 | *.vspscc 97 | *.vssscc 98 | .builds 99 | *.pidb 100 | *.svclog 101 | *.scc 102 | 103 | # Chutzpah Test files 104 | _Chutzpah* 105 | 106 | # Visual C++ cache files 107 | ipch/ 108 | *.aps 109 | *.ncb 110 | *.opendb 111 | *.opensdf 112 | *.sdf 113 | *.cachefile 114 | *.VC.db 115 | *.VC.VC.opendb 116 | 117 | # Visual Studio profiler 118 | *.psess 119 | *.vsp 120 | *.vspx 121 | *.sap 122 | 123 | # Visual Studio Trace Files 124 | *.e2e 125 | 126 | # TFS 2012 Local Workspace 127 | $tf/ 128 | 129 | # Guidance Automation Toolkit 130 | *.gpState 131 | 132 | # ReSharper is a .NET coding add-in 133 | _ReSharper*/ 134 | *.[Rr]e[Ss]harper 135 | *.DotSettings.user 136 | 137 | # TeamCity is a build add-in 138 | _TeamCity* 139 | 140 | # DotCover is a Code Coverage Tool 141 | *.dotCover 142 | 143 | # AxoCover is a Code Coverage Tool 144 | .axoCover/* 145 | !.axoCover/settings.json 146 | 147 | # Coverlet is a free, cross platform Code Coverage Tool 148 | coverage*.json 149 | coverage*.xml 150 | coverage*.info 151 | 152 | # Visual Studio code coverage results 153 | *.coverage 154 | *.coveragexml 155 | 156 | # NCrunch 157 | _NCrunch_* 158 | .*crunch*.local.xml 159 | nCrunchTemp_* 160 | 161 | # MightyMoose 162 | *.mm.* 163 | AutoTest.Net/ 164 | 165 | # Web workbench (sass) 166 | .sass-cache/ 167 | 168 | # Installshield output folder 169 | [Ee]xpress/ 170 | 171 | # DocProject is a documentation generator add-in 172 | DocProject/buildhelp/ 173 | DocProject/Help/*.HxT 174 | DocProject/Help/*.HxC 175 | DocProject/Help/*.hhc 176 | DocProject/Help/*.hhk 177 | DocProject/Help/*.hhp 178 | DocProject/Help/Html2 179 | DocProject/Help/html 180 | 181 | # Click-Once directory 182 | publish/ 183 | 184 | # Publish Web Output 185 | *.[Pp]ublish.xml 186 | *.azurePubxml 187 | # Note: Comment the next line if you want to checkin your web deploy settings, 188 | # but database connection strings (with potential passwords) will be unencrypted 189 | *.pubxml 190 | *.publishproj 191 | 192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 193 | # checkin your Azure Web App publish settings, but sensitive information contained 194 | # in these scripts will be unencrypted 195 | PublishScripts/ 196 | 197 | # NuGet Packages 198 | *.nupkg 199 | # NuGet Symbol Packages 200 | *.snupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | *.appxbundle 226 | *.appxupload 227 | 228 | # Visual Studio cache files 229 | # files ending in .cache can be ignored 230 | *.[Cc]ache 231 | # but keep track of directories ending in .cache 232 | !?*.[Cc]ache/ 233 | 234 | # Others 235 | ClientBin/ 236 | ~$* 237 | *~ 238 | *.dbmdl 239 | *.dbproj.schemaview 240 | *.jfm 241 | *.pfx 242 | *.publishsettings 243 | orleans.codegen.cs 244 | 245 | # Including strong name files can present a security risk 246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 247 | #*.snk 248 | 249 | # Since there are multiple workflows, uncomment next line to ignore bower_components 250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 251 | #bower_components/ 252 | 253 | # RIA/Silverlight projects 254 | Generated_Code/ 255 | 256 | # Backup & report files from converting an old project file 257 | # to a newer Visual Studio version. Backup files are not needed, 258 | # because we have git ;-) 259 | _UpgradeReport_Files/ 260 | Backup*/ 261 | UpgradeLog*.XML 262 | UpgradeLog*.htm 263 | ServiceFabricBackup/ 264 | *.rptproj.bak 265 | 266 | # SQL Server files 267 | *.mdf 268 | *.ldf 269 | *.ndf 270 | 271 | # Business Intelligence projects 272 | *.rdl.data 273 | *.bim.layout 274 | *.bim_*.settings 275 | *.rptproj.rsuser 276 | *- [Bb]ackup.rdl 277 | *- [Bb]ackup ([0-9]).rdl 278 | *- [Bb]ackup ([0-9][0-9]).rdl 279 | 280 | # Microsoft Fakes 281 | FakesAssemblies/ 282 | 283 | # GhostDoc plugin setting file 284 | *.GhostDoc.xml 285 | 286 | # Node.js Tools for Visual Studio 287 | .ntvs_analysis.dat 288 | node_modules/ 289 | 290 | # Visual Studio 6 build log 291 | *.plg 292 | 293 | # Visual Studio 6 workspace options file 294 | *.opt 295 | 296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 297 | *.vbw 298 | 299 | # Visual Studio LightSwitch build output 300 | **/*.HTMLClient/GeneratedArtifacts 301 | **/*.DesktopClient/GeneratedArtifacts 302 | **/*.DesktopClient/ModelManifest.xml 303 | **/*.Server/GeneratedArtifacts 304 | **/*.Server/ModelManifest.xml 305 | _Pvt_Extensions 306 | 307 | # Paket dependency manager 308 | .paket/paket.exe 309 | paket-files/ 310 | 311 | # FAKE - F# Make 312 | .fake/ 313 | 314 | # CodeRush personal settings 315 | .cr/personal 316 | 317 | # Python Tools for Visual Studio (PTVS) 318 | __pycache__/ 319 | *.pyc 320 | 321 | # Cake - Uncomment if you are using it 322 | # tools/** 323 | # !tools/packages.config 324 | 325 | # Tabs Studio 326 | *.tss 327 | 328 | # Telerik's JustMock configuration file 329 | *.jmconfig 330 | 331 | # BizTalk build output 332 | *.btp.cs 333 | *.btm.cs 334 | *.odx.cs 335 | *.xsd.cs 336 | 337 | # OpenCover UI analysis results 338 | OpenCover/ 339 | 340 | # Azure Stream Analytics local run output 341 | ASALocalRun/ 342 | 343 | # MSBuild Binary and Structured Log 344 | *.binlog 345 | 346 | # NVidia Nsight GPU debugger configuration file 347 | *.nvuser 348 | 349 | # MFractors (Xamarin productivity tool) working folder 350 | .mfractor/ 351 | 352 | # Local History for Visual Studio 353 | .localhistory/ 354 | 355 | # BeatPulse healthcheck temp database 356 | healthchecksdb 357 | 358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 359 | MigrationBackup/ 360 | 361 | # Ionide (cross platform F# VS Code tools) working folder 362 | .ionide/ 363 | 364 | # Fody - auto-generated XML schema 365 | FodyWeavers.xsd 366 | 367 | ## 368 | ## Visual studio for Mac 369 | ## 370 | 371 | 372 | # globs 373 | Makefile.in 374 | *.userprefs 375 | *.usertasks 376 | config.make 377 | config.status 378 | aclocal.m4 379 | install-sh 380 | autom4te.cache/ 381 | *.tar.gz 382 | tarballs/ 383 | test-results/ 384 | 385 | # Mac bundle stuff 386 | *.dmg 387 | *.app 388 | 389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 390 | # General 391 | .DS_Store 392 | .AppleDouble 393 | .LSOverride 394 | 395 | # Icon must end with two \r 396 | Icon 397 | 398 | 399 | # Thumbnails 400 | ._* 401 | 402 | # Files that might appear in the root of a volume 403 | .DocumentRevisions-V100 404 | .fseventsd 405 | .Spotlight-V100 406 | .TemporaryItems 407 | .Trashes 408 | .VolumeIcon.icns 409 | .com.apple.timemachine.donotpresent 410 | 411 | # Directories potentially created on remote AFP share 412 | .AppleDB 413 | .AppleDesktop 414 | Network Trash Folder 415 | Temporary Items 416 | .apdisk 417 | 418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 419 | # Windows thumbnail cache files 420 | Thumbs.db 421 | ehthumbs.db 422 | ehthumbs_vista.db 423 | 424 | # Dump file 425 | *.stackdump 426 | 427 | # Folder config file 428 | [Dd]esktop.ini 429 | 430 | # Recycle Bin used on file shares 431 | $RECYCLE.BIN/ 432 | 433 | # Windows Installer files 434 | *.cab 435 | *.msi 436 | *.msix 437 | *.msm 438 | *.msp 439 | 440 | # Windows shortcuts 441 | *.lnk 442 | 443 | # JetBrains Rider 444 | .idea/ 445 | *.sln.iml 446 | 447 | ## 448 | ## Visual Studio Code 449 | ## 450 | .vscode/* 451 | !.vscode/settings.json 452 | !.vscode/tasks.json 453 | !.vscode/launch.json 454 | !.vscode/extensions.json 455 | -------------------------------------------------------------------------------- /LINQTut20/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace LINQTut20 6 | { 7 | internal class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | 12 | // DemoFluentAPI(); 13 | // DemoIEnumerableIQueryable(); 14 | // DemoExecutionOrder(); 15 | // DemoImmediateExecution(); 16 | // DemoDeferredExecution(); 17 | // DemoDeferredStreamedExecution(); 18 | // DemoDeferredNonStreamedExecution(); 19 | // DemoTake(); 20 | // DemoFilterOrder(); 21 | RunQuery(); 22 | Console.ReadKey(); 23 | 24 | } 25 | private static void DemoFluentAPI() 26 | { 27 | // ### Fluent API ### 28 | // 1. Method Chaining and Extension method to make statement look like a sentence. 29 | // 2. is code that reads as a sentence. 30 | 31 | var deck = new Deck(); 32 | var cards = deck.Shuffle(); 33 | 34 | var query = cards 35 | .OrderBy(x => x.Value).Skip(10).Take(10) 36 | .OrderBy(x => x.Suite).ToList(); 37 | 38 | foreach (var item in query) 39 | Console.WriteLine(item.Name); 40 | } 41 | private static void DemoIEnumerableIQueryable() 42 | { 43 | var deck = new Deck(); 44 | 45 | // LINQ to Objects, 46 | // which mostly just does literally what it is told; 47 | // if you sort then pages, then it sorts then pages; 48 | // if you page then sort, then it pages then sorts 49 | 50 | var queryIEnumerable = deck.Shuffle() 51 | .Where(x => x.Value > 5).Skip(5).OrderBy(x => x.Value) 52 | .ThenByDescending(x => x.Suite).Take(5).AsEnumerable(); 53 | 54 | // i.e LINQ to SQL 55 | // Query is being composed (Expression Tree) 56 | // When Execute Provider inspect your query tree 57 | // build the most suitable implementation possible 58 | 59 | var queryIQueryable = deck.Shuffle() 60 | .Where(x=> x.Value > 5).Skip(5).OrderBy(x => x.Value) 61 | .ThenByDescending(x=>x.Suite).Take(5).AsQueryable(); 62 | 63 | 64 | } 65 | private static void DemoExecutionOrder() 66 | { 67 | // Left to right(All Expression in C# are executed Left to Right) 68 | // Understanding the semantics of query execution, can lead to some meaningful optimizations 69 | // Where is not required to find all matching items before fetching the first matching item. 70 | // Where fetches matching items "on demand" 71 | // IEnumerable / foreach / yield Element are not returned at once / one at a time 72 | 73 | var numbers = new int[] { 8, 2, 3, 4, 1, 6, 5, 12, 9 }; 74 | 75 | var query = numbers 76 | .Where(x => 77 | { 78 | Console.WriteLine($"Where({x} > 5) => {x > 5}"); 79 | return x > 5; 80 | }) 81 | .Select(x => 82 | { 83 | Console.WriteLine($"\tSelect({x} X {x}) => {x * x}"); 84 | return x * x; 85 | }) 86 | .Where(x => 87 | { 88 | var result = x % 6 == 0; 89 | Console.WriteLine($"\t\tWhere({x} % 6) == 0 => {result}"); 90 | if (result) 91 | Console.WriteLine($"\t\t\t\tTake: {x}"); 92 | 93 | 94 | return x % 6 == 0; 95 | }) 96 | .Take(2); 97 | 98 | var list = query.ToList(); 99 | 100 | foreach (var item in list) 101 | Console.Write($" {item}"); 102 | } 103 | private static void DemoImmediateExecution() 104 | { 105 | //Immediate: the data source is read and the operation is performed 106 | // at the point in the code where the query is declared. 107 | 108 | // not up to date 109 | // not expensive to call 110 | // list are big 111 | 112 | var numbers = new int[] { 8, 2, 3, 4, 1, 6, 5, 7, 9 }; 113 | var list = numbers 114 | .Where(x => x > 5) // 8, 6, 7, 9 115 | .Take(2) // 8, 6 116 | .ToList(); 117 | 118 | foreach (var n in list) 119 | Console.WriteLine(n); 120 | } 121 | private static void DemoDeferredExecution() 122 | { 123 | // Not executed when constructed, only when it's enumerated 124 | // Setting up a data structure that describes the query 125 | 126 | // queries are always up-to-date. 127 | // queries is more expensive that list to retrieve result 128 | // queries are tiny 129 | var numbers = new int[] { 8, 2, 3, 4, 1, 6, 5, 7, 9 }; 130 | var query = numbers 131 | .Where(x => x > 5) // 8, 6, 7, 9 132 | .Select(x =>x * x) 133 | .Take(2); // 64, 36 134 | 135 | foreach (var n in query) 136 | Console.WriteLine(n); 137 | } 138 | private static void DemoDeferredStreamedExecution() 139 | { 140 | // Deferred Execution(Streaming) : 141 | // at the time of execution they do not read all source data 142 | // before the yield element 143 | // Where is not required to find all matching items before fetching the first matching item. 144 | // Where fetches matching items "on demand" 145 | var numbers = new int[] { 8, 2, 3, 4, 1, 6, 5, 7, 9 }; 146 | 147 | var query = numbers 148 | .Where(x => 149 | { 150 | Console.WriteLine($"Where({x} > 5) => {x > 5}"); 151 | return x > 5; 152 | }) 153 | .Select(x => 154 | { 155 | Console.WriteLine($"\tSelect({x} X {x}) => {x * x}"); 156 | return x * x; 157 | }) 158 | .Where(x => 159 | { 160 | var result = x % 6 == 0; 161 | Console.WriteLine($"\t\tWhere({x} % 6 == 0) => {result}"); 162 | if (result) 163 | Console.WriteLine($"\t\t\t\tTake: {x}"); 164 | 165 | 166 | return x % 6 == 0; 167 | }) 168 | .Take(2); 169 | 170 | var list = query.ToList(); 171 | } 172 | private static void DemoDeferredNonStreamedExecution() 173 | { 174 | // Deferred (Non Streaming): i.e. Sorting, grouping must read all source data before yield element 175 | // Does not mean "this is a sequence that is ordered" 176 | // This is a sequence that has had an ordering operation applied to it 177 | // ThenBy to impose additional ordering 178 | 179 | 180 | var numbers = new int[] { 8, 2, 3, 4, 1, 6, 5, 12, 9 }; 181 | var query = numbers 182 | .Where(x => 183 | { 184 | Console.WriteLine($"Where({x} > 5) => {x > 5}"); 185 | return x > 5; 186 | }) 187 | .OrderBy(x => x) // Buffering: // 6, 7, 8, 9 188 | .Select(x => 189 | { 190 | var result = x * x; 191 | Console.WriteLine($"\tSelect({x} X {x}) => {result}"); 192 | Console.WriteLine($"\t\t\t\tTake: {result}"); 193 | return result; 194 | }) 195 | .Take(2) // 36, 49 196 | .ToList(); 197 | 198 | 199 | var list = query.ToList(); 200 | } 201 | private static void DemoTake() 202 | { 203 | // Take clause just appends a Take operation to the query; 204 | // it does not execute the query 205 | // You must put the Take operation where it needs to be. Remember, 206 | // x.Take(y).Where(z) and x.Where(z).Take(y) are very different queries. 207 | // changing the take location change the meaning of the query 208 | // put it in the right place as early as possible, 209 | // but not so early that it changes the meaning of the query 210 | 211 | var deck = new Deck(); 212 | 213 | var cards = deck.GetSample(); 214 | 215 | var query = cards // { Jack Clubs, 9 Diamonds, 4 Hearts, 10 Spades, 3 Hearts, 6 Hearts } 216 | .Where(x => x.IsRed) // { 9 Diamonds, 4 Hearts, 3 Hearts, 6 Hearts } 217 | .Skip(3) // { 6 Hearts } 218 | .Take(3); // { 6 Hearts } 219 | 220 | var list = query.ToList(); // { 6 Hearts } 221 | 222 | list.PrintDeck("Take more than available"); 223 | 224 | } 225 | private static void DemoFilterOrder() 226 | { 227 | // Filter / Order (Top 10 in the Red Cards) 228 | 229 | var deck = new Deck(); 230 | 231 | var cards = deck.Shuffle(); 232 | 233 | var query1 = cards 234 | .Where(x => x.IsRed) 235 | .OrderBy(x => x.Value) 236 | .Take(10); 237 | 238 | query1.PrintDeck("top 10 red cards"); 239 | 240 | // Order / Filter (red cards in the top 10) 241 | 242 | var query2 = cards 243 | .OrderBy(x => x.Value) 244 | .Take(10) 245 | .Where(x => x.IsRed); 246 | 247 | 248 | 249 | query2.PrintDeck("Red Cards in the top 10"); 250 | 251 | } 252 | private static void RunQuery() 253 | { 254 | var deck = new Deck(); 255 | 256 | var cards = deck.GetSample(); 257 | 258 | var query = cards // { Jack Clubs, 9 Diamonds, 4 Hearts, 10 Spades, 3 Hearts, 6 Hearts } 259 | .Where(x => x.IsRed) // { 9 Diamonds, 4 Hearts, 3 Hearts, 6 Hearts } 260 | .Skip(1) // { , 4 Hearts, 3 Hearts, 6 Hearts } 261 | .OrderBy(x => x.Value) // { , 3 Hearts, 4 Hearts, 6 Hearts } 262 | .Take(2) 263 | .ToList(); // { 3 Hearts, 4 Hearts } 264 | 265 | query.PrintDeck("Order Buffer Sequence, when it's enumerated"); 266 | 267 | } 268 | } 269 | } 270 | --------------------------------------------------------------------------------