Welcome to the fifth episode of my course “Becoming a software developer”, which will guide you through the concept of enumerators and how to deal with the collections.
All of the materials including videos and sample projects can be downloaded from here.
Scope
This episode will focus mostly on the IEnumerable type and all that it’s related to it:
- Debugging in a nutshell
- Extension methods
- IEnumerable
- yield
- IQueryable
- LINQ
Abstract
Debugging is a special form where you can run your code in a so-called debug mode that lets you set the breakpoints and navigate through your code while running the application. You can do a lot of useful things such as choosing which lines of the source code would you like to go to, preview the values of the variables, change them dynamically while running the application and so on. Debugging is mostly used for removing bugs from the application (this is how it got his name), yet it’s not its only task, as it’s very useful in the other areas as well. You can run your code in the debug mode by hitting F5 and set (add or remove) breakpoints by hitting F9 (also by clicking next to the line number). From that point, you can jump between the next lines of the source code for example by clicking F10 or by next breakpoints by clicking F5. To get most out of the debugging you should use the full version of Visual Studio or Project Rider as these two possess the most advanced features. On the other hand, the Visual Studio Code allows to debug your code, but without many special functions which are not available here (but to be honest not needed most of the time either).
Extension methods are a syntactic sugar which allows writing the code in a more fluent manner, just consider the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static class Extensions { public static bool NotEmpty(this string value) => !value.Empty(); public static bool Empty(this string value) => string.IsNullOrWhiteSpace(value); } public class ExtensionsTest { public void Test() { var text = "hello"; if(text.Empty()) { //Do something useful here. } } } |
Can you see what happened? You can invoke the extension method on any type and it can return any value or nothing which would be void. It feels like calling the method that would naturally be a part of the selected type although under the hood it’s just a static method invocation. That’s kind of neat, isn’t it?
IEnumerable is a special interface based on the concept of enumeration. You can think about it as a behavior that allows you to iterate (via foreach which is merely a syntactic sugar over the while loop) through the collection and it’s up to you whether you’d like to extend it. For example, you can use plain IEnumerable
1 2 3 4 5 6 7 8 9 10 11 |
IEnumerable<int> numbers = Enumerable.Range(1, 100); foreach (var number in numbers) { } //This is equivalent of the syntax above (compiler puts it into the <em>try/catch/finally</em> block with <em>Dispose()</em> call, though). var enumerator = numbers.GetEnumerator(); while(enumerator.MoveNext()) { var number = enumerator.Current; } |
Yield is a special keyword used along with the IEnumerable. By using the yield return you can return the next element of the sequence. Simple as that, just take a look at the sample below.
1 2 3 4 5 6 |
public IEnumerable<int> GetThreeNumbers() { yield return 1; yield return 2; yield return 3; } |
IQueryable is of type IEnumerable which means that you can achieve pretty much the same things here, however, it’s very significant to understand why this separate interface was introduced in the first place. Just remember the following – whenever you see the usage of IQueryable
LINQ stands for Language Integrated Query and is a powerful tool which was built mostly as a set of the extension methods that allow filtering, grouping, aggregating, sorting and performing many, many other interesting operations on the collections. You can use either the regular method chaining with lambda expressions or another syntactic sugar equivalent which looks more like the SQL queries. The important thing to remember is that these methods never modify your collection, instead, they return a brand new collection that you can e.g. assign to some variable or keep on processing until you get your results. You can easily play with LINQ by using LINQPad.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public void LinqTest() { var items = GetItems(); var tools = items.Where(i => i.Category == "Tools"); var food = items.Where(i => i.Category == "Food"); var ball = items.FirstOrDefault(x => x.Name == "Ball"); var toolsAndFood = tools.Union(food); var query = items.Where(x => x.CreatedAt >= DateTime.UtcNow.AddDays(-7)) .Where(x => x.Price > 500) .Skip(2) .Take(2) .OrderBy(x => x.Price) .Select(x => x.Name); var anotherQuery = from item in items where item.Category == "Tools" select new {item.Id, item.Name}; } public IEnumerable<Item> GetItems() { yield return new Item("Axe", "Tools", 250, DateTime.UtcNow.AddDays(-15)); yield return new Item("Driller", "Tools", 300, DateTime.UtcNow.AddDays(-10)); yield return new Item("Ball", "Sport", 60, DateTime.UtcNow.AddDays(-7)); yield return new Item("Monitor", "Electronics", 800, DateTime.UtcNow.AddDays(-20)); yield return new Item("Car", "Vehicle", 20000, DateTime.UtcNow.AddDays(-5)); yield return new Item("Bike", "Vehicle", 1500, DateTime.UtcNow.AddDays(-10)); yield return new Item("Notebook", "Electronics", 3000, DateTime.UtcNow.AddDays(-1)); yield return new Item("Mouse", "Animal", 200, DateTime.UtcNow.AddDays(-5)); yield return new Item("Pizza", "Food", 40, DateTime.UtcNow.AddDays(-2)); yield return new Item("Dog", "Animal", 1000, DateTime.UtcNow.AddDays(-3)); yield return new Item("Burger", "Food", 30, DateTime.UtcNow.AddDays(-5)); } |
Resources
- https://www.pluralsight.com/courses/visual-studio-code
- https://www.pluralsight.com/courses/dotnet-debugging-power-tools
- https://www.youtube.com/watch?v=u-HdLtqEOog
- https://www.dotnetperls.com/debugging
- https://www.pluralsight.com/courses/csharp-extension-methods
- https://www.dotnetperls.com/extension
- http://csharp.net-tutorials.com/csharp-3.0/extension-methods/
- http://stackoverflow.com/questions/558304/can-anyone-explain-ienumerable-and-ienumerator-to-me
- https://www.youtube.com/watch?v=4fju3xcm21M
- http://stackoverflow.com/questions/39476/what-is-the-yield-keyword-used-for-in-c
- http://stackoverflow.com/questions/410026/proper-use-of-yield-return
- http://stackoverflow.com/questions/2876616/returning-ienumerablet-vs-iqueryablet
- http://stackoverflow.com/questions/252785/what-is-the-difference-between-iqueryablet-and-ienumerablet
- http://stackoverflow.com/questions/4844660/differences-between-iqueryable-list-ienumerator
- https://www.pluralsight.com/courses/linq-fundamentals-csharp-6
- https://www.pluralsight.com/courses/linq-more-effective
- https://channel9.msdn.com/Shows/Devs4Devs/Introduction-to-LINQ
- http://csharp-station.com/Tutorial/Linq/Lesson01
- http://www.tutorialsteacher.com/linq/linq-tutorials
Next
- Reflection
- Dynamic
- Attributes
- Async & Await
- Parallelism
The sixth episode will be the last one in which we will talk about the features of the language. Of course there are more of them, however, I chose the ones that I found to be the most important ones, especially in terms of writing our application during the course in the near future.
Dzięki Spetzu za kolejny kozak odcinek! Kurs wymiata!
Od 7 odcinka ruszamy z aplikacją?
Dzięki!
W odcinku nr 7 będzie o testach, w 8 trochę o wzorcach i od 9 zacznie się etap tworzenia aplikacji, startując od dywagacji na temat architektury systemu.
Super, nie mogę się doczekać!
A jak planujesz prowadzić projekt aplikacji? Repo, testy, DI, jakiś framework do bazy, wzorce itd (czyli wszystko na mega wypasie jak kurs aktualnie). Czy raczej taka wersja bardziej light?
Tak, na pewno takie rzeczy się pojawią, bo to podstawa dobrego projektu, aczkolwiek np. w stylu TDD to raczej prowadzone nie będzie, bo by trwało zbyt dlugo :).
Pingback: Dew Drop - February 23, 2017 (#2428) - Morning Dew
Witam!
Super seria kursów.
Wielki szacun za to co robisz dla community początkujących programistów ale także takich jak ja (4 lata doświadczenia ale w innym języku i w firmie w której się tylko wytwarza bez dbania o jakość) . Dzięki tobie nabrałem motywacji do własnego pet project oraz do zmiany ścieżki kariery.
Pozdrawiam
Cześć,
Dziękuję, cieszę się, że się podoba :). Robię to z różnych powodów m.in. tego, że chcę się sprawdzić w roli nauczyciela, przekazać solidne podstawy, które są często pomijane w tego typu kursach (bez przełożenia na rzeczywiste aplikacje) i też w jakiś sposób się rozpromować.
Super słyszeć, że nabrałeś motywacji :D.
Pozdrawiam!
Pingback: Becoming a software Developer – episode V – Patryk Huzarski | Personal Blog