Complete Practical LINQ Tutorial in C# | Elias Spock | Skillshare

Complete Practical LINQ Tutorial in C#

Elias Spock, Chance favors the prepared mind.

Complete Practical LINQ Tutorial in C#

Elias Spock, Chance favors the prepared mind.

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
70 Lessons (4h 46m)
    • 1. Course Overview

    • 2. 01 Outline

    • 3. 02 LINQ is Everywhere

    • 4. 03 Extension Methods

    • 5. 04 Pipelining

    • 6. 05 Why LINQ

    • 7. 06 The Role of IEnumerable

    • 8. 07 Extending IEnumerable

    • 9. 08 ParsingCsvFile

    • 10. 09 Named vs Anonymous vs Separate Methods

    • 11. 10 QuerySyntax

    • 12. 12 YieldReturn

    • 13. 13 LINQ Deferred Execution

    • 14. 14 Exceptions and LINQ

    • 15. 15 Multiple Enumeration Pitfall

    • 16. 16 Altering List

    • 17. 17 Conclusion

    • 18. 01 Outline

    • 19. 02 Range Repeat Empty

    • 20. 03 Generating Random Numbers

    • 21. 04 Conclusion

    • 22. 01 Outline

    • 23. 02 Select

    • 24. 03 Where

    • 25. 04 ThenBy

    • 26. 05 First, Last, Single, OrDefault

    • 27. 06 TakeWhile and SkipWhile

    • 28. 07 SequenceEqual

    • 29. 08 Distinct

    • 30. 09 Any, All, Contains

    • 31. 10 SelectMany

    • 32. 11 ElementAt and Counting

    • 33. 12 Conclusion

    • 34. 01 Outline

    • 35. 02 Join

    • 36. 03 GroupBy

    • 37. 04 GroupJoin

    • 38. 05 Zip

    • 39. 06 Min, Max, Sum, Average

    • 40. 07 Concat and Union

    • 41. 08 Intersect and Except

    • 42. 09 Conclusion

    • 43. 01 Outline

    • 44. 02 OfTypeCast

    • 45. 03 ToArray, ToList, ToDictionary, ToLookup

    • 46. 04 Pitfalls of Conversion

    • 47. 05 Conclusion

    • 48. 01 Outline

    • 49. 02 XML Document Structure

    • 50. 03 Creating XML from a Collection

    • 51. 04 Refactoring Code

    • 52. 05 Reading XML

    • 53. 06 Conclusion

    • 54. 01 Outline

    • 55. 02 Preparing the Project

    • 56. 03 Inserting & Reading

    • 57. 04 Pitfalls of LINQ to Entities

    • 58. 05 Expressions, AsEnumerable and AsQueryable

    • 59. 06 Conclusion

    • 60. 01 Outline

    • 61. 02 Defining Functional Programming

    • 62. 03 Functions Are Everywhere

    • 63. 04 Why Functional Programming

    • 64. 05 Immutability

    • 65. 06 Purity and Side Effects

    • 66. 07 Extending IDisposable

    • 67. 08 General Extensions

    • 68. 09 Extending StringBuilder

    • 69. 10 Primitive Obsession

    • 70. 11 Conclusion

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

Extension methods were introduced in C# 3 and since then became an indispensable part of the .NET platform. That enormously powerful feature allowed to build a whole framework built upon it called LINQ or Language Integrated Query. I’ve seen many code bases which avoid using LINQ and rely on the old procedural style of programming. If you still feel uncomfortable with LINQ or you want to improve your understanding of LINQ, then this course is for you.  As you might know, LINQ was inspired by functional paradigm and F# in particular. So, this course is not only about LINQ but about the fundamentals of functional programming as well.

This course covers:

  • The basics of LINQ: extension methods, the idea of pipelining, IEnumerable, implementing our own extension, query syntax, pitfalls of LINQ operations, how to alter a list

  • Generating data streams: Enumerable class and its main operations, implementing your own extension which generates a stream of data

  • Filtering, Ordering, Projecting: Parsing a CSV file, ThenBy, First, Last, Single, TakeWhile, SkipWhile, Any, All, Contains, SequenceEqual, Select and SelectMany

  • Joining, Grouping, Aggregating: Join, Group, GroupJoin, Zip, Sum, Average, Min, Max

  • Conversions: OfType, Cast, ToArray, ToList, ToDictionary, ToLookup, AsEnumerable, AsQueryable

  • LINQ to XML: overview, generating XML from a collection, reading XML

  • EF and LINQ: Expression Trees, Inserting  into and Reading from a database

  • Extendibility in C#: what is functional programming (FP), purity and side effects, extending IDisposable, general-purpose extensions, extending StringBuilder, Primitive Obsession

In short, this is a great course, so enroll right now and start learning LINQ and the fundamentals of functional programming.

Meet Your Teacher

Teacher Profile Image

Elias Spock

Chance favors the prepared mind.


I'm thankful enough for that I love what I do.
I began my career as a postgraduate student participating in Microsoft ImagineCup contest.
I've been working with .NET platform since 2003. I've been professionally architecting and implementing software for nearly 7 years, primarily based on the .NET platform. I'm passionate about building rich and powerful applications using modern technologies. 
I'm a certified specialist in Windows Applications and Service Communication Applications by Microsoft.
I'm one of the coordinators of the MSK.NET User Group in Moscow.

"If it's work, we try to do less. If it's art, we try to do more." - Seth Godin.

What I can say is that software is my art.

See full profile

Class Ratings

Expectations Met?
  • Exceeded!
  • Yes
  • Somewhat
  • Not really
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Your creative journey starts here.

  • Unlimited access to every class
  • Supportive online creative community
  • Learn offline with Skillshare’s app

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. Course Overview: Hi. This is injury spark from injury spark dot com, and they'll be leading you through the course. I've been working with the dot net platform since 2003. I've been professionally architect ING and implementing software more than 10 years, primarily based on the DOT That platform I'm passionate about building reach and powerful applications using modern technologies. I'm a certified specialist in Windows applications and service communication applications by Microsoft, and I'm one of the co organizer's off the most kudos that user group in Russia. And here's my teaching approach. No fluff, no ranting, no beating the air. Steam your time course material is succeed. Yeah, comprehensive. All the important concepts are covered particularly important topics not covered in depth for absolute beginners. Offer my help on Skype absolutely free if requested. Take this course and you'll be said it's fine. Extension methods were introduced in C Sharp three and since then became an indispensable part off the dotnet platform that enormously powerful feature allowed to build a whole framer built upon it called link or language Integrated query. I've seen medical basis, which avoid using link and rely on old procedural style of programming if you still feel yourself uncomfortable with link or you want to improve your understanding off link, Then these courses for you? Yes, you might know Link was inspired by functional programming paradigm and F sharp in particular. So this course is not only about think, but about the fundamentals. Functional programming s well, so they scores covers the basics of Flink, including extension methods that idea off by blinding power off innumerable, implementing our own extension query syntax, beautiful offline corporations and how toe alter at least generating data streams, including innumerable class and its main operations. And implementing your own extension, which generates a stream of data filtering, ordering and project, including Farsi SCS file. Then by first last single take wilds keep while any all contains sequel, sequel select and select. Many operators provided by Link joining grouping and aggregating, including joint group group, join Zip some average mean max operators provided by link conversions, including off type cast to array to least two dictionary to look up s and Loomer esque wearable operators provided by Link link to XML, including the overview generating maximal from a collection and reading maximal filed entity, Framework and link, which is called blink toe entities, including expression trees inserting inter in the reading from a database and extended Billy teams to shop a separate top, which includes what is functional programming purity inside the facts, extending I disposable general purpose extensions. How to extend string builder and primitive obsession. In short, this is a great course, so in role right now, I'll start learning link and the fundamentals off functional programming. 2. 01 Outline: Hi. This is Engineer Spark from injurious park dot com, and we started our journey from the basics. In this section, you learn what is link the future of extension methods. What is by blinding and methods. Cheney. Why link is so cool You'll see the power of innumerable. You'll implement your own extension method. Well, look, A name methods versus anonymous methods versus Lambda us. You'll see the query. Syntax classifications, off link operators. What is yield a return link? The problem of deferred execution. He exceptions and deferred execution closures with foreign for each loops and how to alter a list. Let's kick off this section by talking about what is linked at all. 3. 02 LINQ is Everywhere: link stands for Land, which integrated query, and it is a framework, which was introduced along with the release off C. Sharp three. Link was inspired by functional programming concepts, and now it is an indispensable part of the dot net Blatt firm to use link framework. You should add the system that data package or system dot xml that link to use linked to XML. I don't mean 99% of cases you don't need to do anything manually, since these packages are fundamental and almost always are added to a project created via a project template in the visual studio. So basically, you can just start writing Lee inquiries, though, as I said, if visual student doesn't recognize the method about which will talk in this course, just add system that data as a reference to a project or system that XML that link back in times before a seizure Up three, you have to write your own custom code to query in memory objects. You had to use a deodorant, now have to access data in database and then write queries in C sharp to resulting teeples of data the same you had to do with XML. You had to read and write it by XML Arena Writing all the cold which manipulates XML loads manually link abstracts away these things so you can use it everywhere to query any data objects Sequel data basis mongo db CC vials XML Jason File System link is everywhere, and I'll explain how to use it in this course, and after that you will be able to query any data from any source. 4. 03 Extension Methods: extension methods were introduced in C Sharp three along with the link framework. Actually, Link is based on extension math. It's heavily functional. Programming is based on extension methods. Heavily us. Well, you'll see later how we build functional constructions with the power of this feature. The power of extension methods is enormous. With that featured our disposal, we can extend any existing type limitless Lee. In this lecture, I'm going to show the basic mechanism of how this Fisher works. So extension methods allow us to add functions two types which we didn't develop. For example, you can add methods to say this string builder type and use those methods is they were always there. Implemented by the string builder from the day one extension, methods allow extent types, including classes, structures and into faces, extent generics, including generic classes, structures and into faces. For example, you can easily extend the list of tea or specifically i innumerable of tea. This allows to simplify our code base very often to add functionality to any class which participates in a class hierarchy without extending the hierarchy and without composition. By creating separate classes, well sometimes need to add some functionality to an existing class and doing that by inheritance. We often violate the Lisk of substitution principle, or just couple classes to tide extension method allowed to avoid such unfortunate consequences. Though extension methods also can be abused, you'll see how extension methods can signal eyes about the arising problem called primitive obsession. Improper use of extension methods become a harbinger off that anti pattern in such cases. Okay, let's switch to visual studio and look at a simple, though a real world example from my own practice. I work for a company which produced devices on microcontrollers with low memory programs written for those devices. Always store dating, specific, unusual for months. Low level programmers don't like to live easier. They love when their lives are hard. This hell, this is a joke. But those who ever worked with low level programmers know what I'm talking about. There was a case when my high level program, written in C shop, needed to communicate with such a device, passing date and time values. He was specific formats supported by those low level devices. Here you can see how date and time various looked like on the low level device. There were two cases and don't ask me how they merged. This is how the reality looked like after the year in 1999 the correct format started with four digits, which is the year then two digits represent a month. Then two digits is the day and then the time part where the 1st 2 digits is the hour than minutes. And finally, the seconds before the year 2000 the format was a little bit different. The year part was expressed only two digits. That low level program knew that the century was 19. My program contained regular daytime instances, and I needed to convert them properly by the virtue of a single call. In a daytime instance, we can't dig the sources of the daytime structure and add any methods, but we can extend it with the power of extension methods. To write an extension method, we need to host it inside the state of glass. Let's great aesthetic daytime extensions glass. Now we can write our extension method. I let the signature as you can see the functional add. It is also static. An extension method has to accept an instance of the type it extends in this case, we extend the daytime time notice that we also need to add the these keyword before the type name. You're free to add any other arguments without these keyword. In addition to the first argument which has to represent the type we extend which must include this keyword. Now we can implement the functionality. - This is a pretty simple implementation, but look at how natural now we can use this functionality. - Yes , you can see the device. Format matters is available as it was always implemented by the daytime structure. Looks like this method is native to the daytime type. Let's run the code and check if everything works as expected. Yes, everything works fine. Actually, we could spend some time on learning all the nitty gritty off extension methods. But the basic understanding of how to write extension methods is enough in 99% of cases. So let's look further and learn more about auto properties and the mutability. In the next lecture 5. 04 Pipelining: by planning is a technique which allows and out off one function to be passed to the next one. This allows organizing the natural flow of data. At first, let's consider a counter example. Consider the next code snippet. The reading order off this coat is reverted from the human point of view because in order to understand the meaning of this code, you have to read it from the innermost statement to the outermost. Sometimes you can find yourself writing such cold with foreign five levels off nasty. Why would write code like this? This is because we don't want to introduce unimportant intermediate variables like in the following example. The previous gold sample is rewritten here with intermediate variables. We don't like such cold as well as the previous one we have here meaningless variables. We actually don't need them by planning. Is this so neat and powerful technique that, for example, F. Sharp has a so called by blind operator? The previous example would look like this Enough shop. This coat can be read naturally because it goes straight forward. Unfortunately, we don't have such an operator building so shop. Whether we can do about that is to chain methods. Methods. Chaining is a functional style architectural better, which has to be supported by types, since the programming language does not support by planning explicitly link you was designed bearing in mind functional concepts like by planning. That's why you can chain methods like Ranch, where ski P two least and so on. Another example. Off methods. Chaining without in Q is the string builder, which was developed in such a way that you can change depending methods. Here is an example. This is possible because a pant Abend line and depend format methods return updated string builder object instance. That's why you can change these methods. Using the power of extension methods, we can transform the code on the left side into the following on the right side. 6. 05 Why LINQ: So let's look at the difference between code rating, procedural style and gold ridden with link in functional style. I would notice that I had a two folders, chest stats and students stats into the project, which contains some statistics in CS Avi Files. Let's compare how code, which displays the five biggest files, will look like when we use Link and we and when we don't use it. So at first I'll calculate the path where the statistics resigned and I'll call the display largest. Instead, files method without Link. Passing the location in hell. Generate the method. So it first I'll take the information directory director info, besting the Beth. And after that, I'll take all the files from the directory calling get files, and after that we need to sort all the files. I'll do that with the air, a sort method passing files and alarmed expression, which implements the sorting algorithm. It should compare the length of files with each other. So if X length is equal to via length, then I'll return zero. Since they're equal. If X length is greater than why length, then I'll return one and other wiles, and otherwise I'll return minus one. Yep. And let's run a for loop from 0 to 5 to display the 1st 5 biggest files. And let's display the name of the file and how much memory takes on the disk. So this is how the code looks like, which displays the five largest files when we rely on the imperative for procedural style. So let's compile the application and run it, and you can see the output the five biggest files in that directory. So how to improve this code? We can improve this code by using the link. So let's go. The display Largest stat files with Link method again besting the location. L generate this method and a look at and how much powerful link is how it enables us to write the same code in a functional style. So I create here a directory in full get files, and I'll build here a chain of goals. Get files, returns and the ready and arrays implement the innumerable interface. So we're able to apply here link operators so I'll import here the system that link library assembly, which implements the where operator, and I'll use it. Let's, for example, here filter the files by the last write time. I want to see here the files which were created before the first off August, and then I want to order them by length and then I'll take the biggest five. So I'll just take five elements. Those will be are those will be are the biggest ones. And finally I'll around the for each loop, displaying some information about these files. So the results are the same, except the fact that we actually filtered. They files by the last write time. In addition, so look at the difference between the procedural and functional. Written with Link Gold soap. This code is awful, and the code with the link his marbles. It's beautiful. It's gonna size. And so this is a very powerful approach, which allows to right very reliable and powerful code, So use link whenever you can use link to squaring any least off objects. Any collections 7. 06 The Role of IEnumerable: link is based on extending the innumerable interface. So what is innumerable? What is it? I am memorable exposes the get in numerator method. So let's write a piece of coal to demonstrate something. Erase this well as's collections implemented the same interface innumerable. So, for example, we can assign the least collection to the innumerable and let's initialize it with a couple off strings. Let's say John and Bob and Ellis, I said that innumerable exposes the getting numerator method. That method returns another interface i e. Numerator, which exposes move next current and reset a prime members. In other words, we can calling the getting numerator method on the names collection we will get to the I a numerator of string. So here it is. Names don't get in them a raider and we can organize the loop Well, loop iterating over the narrator collection which is off in the murder of string type. And for that for iterating over these collection, we can use the move next method and the U property current to take the current element. Very sad gets the date aerator to the beginning of the collection and let's right to the console. Some information here. So in this case, I'll just ride the current, which is string. These will be the names we added to the list. Let's look at the result and it works. Link is based exactly on the i innumerable interface. So all the extensions link extensions are based on the I am a memorable and I quit arable interface and we will look into the Equitable into face a little bit later in the course. So the main thing you should remember is that erase collections, implement the innumerable interface and it means that they support the link operators. And this example demonstrates what is innumerable exactly. It abstracts away, another into face. I am numerator. So the forage loop actually inside itself uses exactly this code to reiterate over a collection. So this is what I innumerable actually is. 8. 07 Extending IEnumerable: So let's start it. How to implement your own extension method for the I innumerable interface. For example, in the case we looked at, we can implement our old filtering method instead off where and actually we can implement the for each extension to get rid off these for each loop. So I'll create the class right here. It has to be a static one, since extension methods should recite in state of glasses. I'll name it link extensions. So all the extension methods are public and ST ick, so I'll define one. Uh, it's going to be a public stated feel Turn Off T, which returns on innumerable lifting it except and I innumerable off t. So let's named Collection. And by the way, it should take a delegate off the funk type, which takes the tea. And Bullen it's It's a practical. So I limped, mounted, not correctly, and you'll see later why this is, for the sake off learning for the sake of teaching. So I'll create ah collection at least of teen, and I'll run the for each loop iterating over the result and if predicated returns to, Of course, I passed the item into the predicated. So in this case, I add these item to the A resulting list. And finally we just returned the result and going the same way. We can implement another extension named for each, so it returns void. And by the way, I for forgot to uh, right here. These This is a requirement for writing any extension methods. In this case, we're going to take action. We can generate here, and I'll check. Let's do that and the same for the action. And let's run here if Ridge Loop calling the action and passing the current item. So extension methods are here and we can use them. So let's move this class into a separate file, which will be named link extensions. Not surprisingly, I'll get back, and I'll replace the call to the wear method by our filter, and I'll get rid off the forage loop. So here I am going to use the filter method, passing absolutely the same credit, and everything works fine. And finally, let's apply the for each extension, passing with the the same expression console right line, blah, blah, blah. So, behind the scenes, I moved these methods to this separate a class and I need to called the run method the dama method from the main method. Let's around the up and we can see there absolutely the same result but with our extension methods. So this is how we can write our custom extensions for the innumerable ing to face and by the way, not only for the innumerable into face. Very often we need to write our own custom extensions which are not provided by the link framework or by the more ling framework. So we really often used the power off extension method seen see shop. 9. 08 ParsingCsvFile: Let's demonstrate the power off link on another example on example, where we're going to parse a CCT file for feeling a collection off just players. So at first, let's create a glass, which I'll call just Blair. It will contain several fields more concretely, properties and in addition and I d property. Yep. And uh, let's override the to string method Alco pee in peace prepared code snippet and for parsing string from a sissy file. I'll define a public ST ick method, which returns and instance off just Blair, and I'll call it bars. Feed there, says V, which takes a string. And I'll split that string by calling the split method passing the Colin. And, uh, yeah, of course it's an array. And let's parse the area of strings here right away, directly referring to specific indexes. So the idea goes first than less name. And actually, there is a name with the last name separated by a comma. So here I spill it again, passing comma, and I dream, um, empty spaces and the same goes here. But we're going to take here the first index and several remaining properties, country rating and birth year and Now we can write code using link for filling collection of just blares slip life filters display top 10 players, for example. Let's look at how we can do that. At first, I'll take a folder where the file we're going to parse recites for the time called Path Combined. Passing the current directory and the file is named top 100 chihs players dot c. S v Andi. Let's go here the PARCC method passing file Occasional generate this method and let's define the list. Yeah, and we call here file a riddle lines So we want to read all lines from the CCT file. Raedle Lance returns an innumerable of strings. After that, we will skipper the first string. Since it contains names off columns, we don't need it. Need them. And using the Selic method, we're going to project allow the strings using the parsing method, we just throat and, for example, we can filter the players who by their age, So, for example, I can take players who were burned after, uh 1988. And after that I can order them by the skin ending. Um, I mean by the scanned ing and by rating and let's take only 10 players. So these are going to be top 10 players and we can Narada for each loop we can use. Ah, an extension instead off direct for each loop. And we can pass an instance of player because we over ridden who have overridden the clustering method and we can run the application and look at the output and was seat up. 10 players cooler burn after 19 88. So this is how we can use link to parse CSE file to project to filter in tow, order and so on. So link is very powerful. Let's look at what we can do with link further. 10. 09 Named vs Anonymous vs Separate Methods: in general who have three ways off working with delegates. Well, let's say that we have a list with ratings, the least off ratings of type into drink. And let's say we want to filter the ratings taking those which are greater than 2700. And for that we can use this standard where method integrated into link framework. Let's use it. So the first way off working with delegates is to rely on Lambda expressions. This is the most succeed syntax. So in this case, we're determine the input perimeter its name are, and if the expression is simpler, we can avoid writing curly braces and just write the expression ST um, another option used to create a separate method. Let's say I'll name it. Get ratings over 2700. It's a separate method, but we use this option. I mean, we create a separate method when the expression is not a one liner, but let's say it takes three or five or more lines of code. So this is a complex expression, which really should be a separate method, so it would be quite ugly. So in such a case, we create a separate method and another option used to rely on an anonymous method which you can write using this syntax writing delegate. Then determine the defined the parameter. And actually this is the same asked the land expression, but much more wordy. So if you decided to use a delegate I mean and and an anonymous math it, then you should stick with their land expression, since it's more succeed. So in more expressive. So actually there are two options. The 1st 1 is to rely on the Lambda and another one if you have a complex expression to create a separate method. And, of course, if we're on the forage loop iterating over these three collections, we will end up with absolutely the same results. And yet you can see that the results are the same. Absolutely the same yet, So all these options work the same, producing the same results, and actually before C sharp, three left expressions have not been presented, so you could use only anonymous methods or past separate methods. 11. 10 QuerySyntax: link supports specialists in tax, which is called Queer Issing Tax, which is very similar to sickle. I'll comment out here this part of code, and I'll demonstrate how to use that syntax. So, yeah, that's, um, separate the where, on order by the scanning and take and let's arraign plant these sparked by using the inquiry syntax. So I'll begin from a key word from Than Player goes in in a collection in list. So Player is an iterated, er, so to speak. It's an instance of just Blair, and we can use here in the where clause, too filter them by the birth year. And after that we can order them by a rating and by the scanning. And finally we have to write Select Player, and these is an absolutely the same query. But truly speaking, I didn't use this in tax. Yeah, sometimes, Ah, these syntax can simplify complex think query, But I should say that it's a rare case. So this in tax has some peculiarities. For example, it has keywords like Let I didn't show you hear that keyword and ah, there is a moment that any kind off link expressions can be implemented by the leather chains. But not all the link queries can be implemented via a query. Syntex. It's a rare case, a swell, but in general the chain off methods is more powerful than a syntax, uh, which looks like sequel so you can use the syntax, but and my practice, I always use the chain of calls to methods, and in this course, I'll use the chain of methods, not they sickle like syntax. So I can demonstrate here that these two queries will work the same way. And, uh, yeah, I didn't take 10 players in the sequel likes in texts, so but basically the output is the same. So the this query is working. 12. 12 YieldReturn: I already said that the filter method we were implemented the filter method not right. Let's get back to that method and re implemented. Let's compare this method with the Where method built in link. What's the different between them? At first, I'll call the filter method. I'll call it Demo No Yield. And after that I'll call the demo yield and they'll generate these methods. And here I'll get the players using the Get them a list method. We don't have it right now. L generated. This is a state of method, which returns a collection off Blairs for demonstrating purposes so it returns and nine memorable in Elko Peon based some cold here, which I prepared. So now I'll filter the players by, Let's say, country for that I call the filter method are extension method and I'll around the for each loop by this collection, displaying the information about these players and let's implement absolutely the same, but using the wear method which is built in the link framework. So I'll just to replace the filter to where and to see the difference we need to change the implementation of the country property. I'll transform it to the proper to with the backing field, and I log the access to get her. I look to console, displaying some information. Let's say Log Country, let's get back and let's run the application. Let's look at the results to filter method at first logs all the countries and then displaced those countries. We need those players. We need yield works differently. It displays the player as soon as it sees the player, which satisfies the condition. This is because it is implemented differently. So it is. It is implemented via a yield return statement. So actually what? What is the difference? Let's commend out here the forage loop and for each here, where we use filter and let's compare it out. I'll run the application again. And when we he was filled her there were access to all the players. And when we use where nothing has been locked, if this is because no access have been so. The thing is that all the link operators, almost all the link operators, are built with the power of field, a return operator which provides a deferred nature off executing the queries. So if there is no forage loop or a loop, which generates over a collection than all the operators, like where quarter by and other they will not be executed at all. So this is because they're implemented fire yield, return not Phoenix police it it aeration over collection and then creating another one. So they are implemented like this. No comment out these lines and I'll say here yelled Return item! And if we around our replication once again in both cases so we don't see anything. So for now, where and filter are implemented the same and we need to get back our for each loops and right now are queries work absolutely the same way. 13. 13 LINQ Deferred Execution: developed. Many developers forget how link actually work, so we need to stay this example. Let's get to the code without rambling too much. Here we have a list of integers. It contains three values. After that, we're all the way RL ng method, which accepts alarmed expression. In this case, we filter all the numbers which are greater or equal to then a gram of three from the initial list, and then we just bring out the number of items in the quay released. So what do you expect? It will be printed out if you answered one and you're right. Link methods can be divided into two groups. The 1st 1 is deferred methods and the 2nd 1 is greedy. Methods. Differed methods are the following select select many take skip where and others the greedy one sort of the following count average mean max some first last two least two array and many others so greedy operators, when called, forced to run all the previously constructed link expressions. In our case, there were expression will only be executed as a result of calling the count greedy method . But before calling count, the third item will be removed explicitly via the removed method, so the end result will be one scenes. There is only one element which is greater or equal to two. Be careful with this stack. Overflow is full of questions related to the specific behaviour. Offline cooperators, the full list of operators and their classifications can be found inside the link I attached to this lecture off course differed Execution, apart from being dangers, is actually beneficial from the performance point off you. In case clients code doesn't want to process all the items in the collection. There is no meaning toe allocate member for all the items and this is what deferred execution allows it allows to avoid excessive iterating saving execution time and memory. 14. 14 Exceptions and LINQ: that fact that the execution offline cooperators is deferred leads to particular consequences. Let's pretend that the access to the country proper team leads to an exception. Let's say an invalid operation exception will be thrown when we access to the country property. So what will happen here, where an exception will the throw and the exception? Yes, the result of calling the wear method will not happen, and the exception will be thrown on Lee. Well, way to rate over a collection using the four ish loop. Let's demonstrate that I'll surround the first look by try catch blocks and lo cure some information to the console. Let's come in town this method when I've needed Let's run the application and you can see here that the invalid operation exception being thrown and it was thrown. When will we around the for each loop. So if we command out the for each loop, that exception will not be thrown, so you can see here that, you know, exception had been strolled. So you have to be careful with exceptions that can be thrown from within link operators. And remember about these behavior 15. 15 Multiple Enumeration Pitfall: there is a hidden people caused by deferred nature off execution offline queries. Let's demonstrate that problem. Let's say I have a method which fielders chest Blair's buy rating. I'll call it filter players buying minimum rating. So I will define a private ST Ick I innumerable off just player method called Fielder by, um, filter players by minimum operating, which accept an integer cold rating. And it's returns that query to the Dem A list. I'll call where passing lmt expression, which filters players by rating greater or equal. Then I mean rating like So let's see, we have a math which calls that filtering method. I'll call it Private stated Avoid. It's going to be a demonstration method. I'll call it multiple in, um oration, which demonstrates a certain problem. Let's call that fielder players method passing some value and get to the result into the players. Variable. Okay, Very often we need to reiterate more than lawns over collection, performing different actions related to logging, transforming, projecting and other things. I'm not going to come up with bright ideas of what we could do with our collection of players, so I'm just going to it rate over that collection twice. At first I'll log all the first names and then all the last names. So I'll say First names. Then I'll Arana for each loop over the players, passing player dot first name and the same ghost with the last name off course. We could do that in one shot, but that's not always the case. Very often, we really need to reiterate over collection more than once. So do you see here a problem? Indeed, the problem is hidden here. If I hover my mouse over the collection used in the forest loop re Sharper says possible multiple in new Marais Shin off by innumerable What does it mean? I hope you keep in mammary that mainly inquiries are lazily evaluated or deferred, and the actual it aeration fires up when we're on the for each loop. In this case, who have to forage loops, and each time we're on the for each loop, it incurs a re evaluation off the wear operator inside the filtering method. Instead of performing only one filtering, we're on here, it twice. Players will be filtered by rating as many times as many times we're on forage loops, iterating over the resulting innumerable. By the way, if that filtering method would access database, things could go much worse. For example, at the first forage, you could iterating over one set off date, and at the second forage, you could get a rate over another set of data. Since the state off, a corresponding table in a database could be changed between the forage loops. Another bat scenario is that the collection being filtered could contain millions of records. I think you understand the consequences off running Aware operator twice over such a big collection instead off running it only once to defeat the problem. You should matter. Realize the results off a query as soon as you got them calling any greedy operators such as to least or to arrange. For example, I'll call here to list, and this is going to be they'll list off chest Blair's. You can see now that every sharper doesn't suggest me anymore, that there can be a potential problem with multiple enumeration. And finally, I would discuss another interesting point regarding the problem off multiple in generations , let's say you need to expose public method called Process Collection, which takes a collection as an argument, and it rates over that collection several times. What would he request in the signature off such a method? By innumerable off a certain type, say, just Blair like that. Look at this private ST ick. Let's see. Void process collection. I innumerable off just players cold players like So, do you think that clients would issue that your method? Will it rate over collection more than once, let's say we have here of the same two for each loops. So the question is, do you think that clients would assume that your method will iterating over a collection more than once? Who? Who knows? One could pass irregular query with potentially millions of records, which will be materialized while in Yuma rating that collection. In such a case, I would better either request at least or I read only collection, which appeared in dotnet 4.5. Like So I list or I read only collection. When we request to these kind of types, a caller will not be able to pass a query materializing the results of which would lie on our shoulders. So considered the streak. Next time you need to request a collection as an argument, avoiding the potential problem off multiple and M orations 16. 16 Altering List: Very often we face the case when we need to change an existing list of fightings. Look at the following examples here we have a regular released off integer values we to rate over the leased using a forage loop. We try to remove all the even numbers from the least within that loop. In the end, we have an assertion in the form off console right line. So what will be printed out to the console? Okay, let's run the cold to look at what will happen at run time. Whoops. An exception has been thrown. Why does this go throw an exception? This happens due to the fact that collections used in the for each loop are treated as immutable. Have you ever thought what it is for? Each loop for loop is clear and straightforward. It is based on the operator, you explicitly setting the force statement. But what about the forage loop? It seems that there is no operator from the first sight. However there is. Please remember that the for each loop is a short version off the following code the compiler expensive for rich loop into something like this we get an in numerator here, which has a method moved next to move the car. Sir. Within the collection, we get current values by calling the current property. This is done in a while loop to reiterate over the whole collection. If you look inside the move next method, you'll see that there is a hidden check which ensures that the collection was not modified . If it sees that the collection was modified, it will throw an exception. So how Toe alter an existing list? There are three major ways to achieve what we want. The 1st 1 is to use a for loop. Look at this coat. Here we have a regular for loop, which starts from zero and goes up to the count off list. The list is modified within the loop. I am not going to run this girl. Believe me, it works as we expect. Looks like this is a pretty easy way to alter. Released However, let me introduce one change to these piece of code. Seems like this change is not related to how the look works, but what will be printed out here now you could think that everything should be fine and the resulting least will contain only four and five. Let's run the code and set a break point inside the loop. I'll go through the loop step by step. Do you see this? We removed the first item. One is that the zero index, but the Toray Ter equals one. As a result, we skipped the step off, comparing the item at zero index. After the first item is being removed, I'll remove this break point and set another one at the end of the method. Let's see what the list contains now. 13454 items instead of two. To fix the problem, we also need toe alter the it aerator along the way. Let's around the code. Everything works fine. In theory, this method off altering at least should work fine. However, we can still rely on the for loop, avoiding changes off the curator variable. Let's expend another method. Look at the for loop. They sloped goes backward. It starts from the last item and goes to the 1st 1 The trick is that removing items within such a loop incur changes off. Only those indexes were already not interested in because we passed them. I'm not going to run the code. I'm sure you see that it will work. Indeed. Unfortunately, both ways are not always applicable. When we have some sort of complex rules, we have some hidden into connection between items. Then we may need another, more robust way. In case of a simple condition. The most robust weight is to rely on the special link method called Remove All which accept alarmed expression. The remove all implementation takes all the responsibility off, altering the least itself the most robust weight alter. The list is not toe altering it all. Yes, sounds funny, but this is how things work. So the most robust ways to create a separate least and filter the initial one. Here's an example of how to do this with help off link. Here we have an initial least, and then we declare the 2nd 1 We filter all the odd numbers and add all the remaining items to the newly grated list. In this case, I call the greedy operator to least to immediately return you filtered collection. This way does have a problem with excessive memory consumption. In certain cases where we're processing millions off items in simple cases, this is a pretty good way to go. In short, there are the following ways off altering an existing list. Alter within a for loop, going backward, older within a for loop, modifying the generator. Alter calling the removal method and alter by introducing an additional least, this is not about altering at all, but actually it's often sufficient to achieve what we really want. 17. 17 Conclusion: congratulations. You learned the fundamental So Flink. Let's recap what you learned Link stands for language, integrated query and it is a query language which abstracts away the technology off accessing data stored in different sources. Link is heavily based on extension methods by blinding is a functional programming concept , and it is implemented in C sharp as methods. Chaining link is very powerful because it allows us to use the same technology for accessing different sources of data and do it declare a tiddly what improves irritability and maintain ability off a code base. I innumerable is a simple yet powerful interface which abstracts away the concept off it irritable collections. It is a fundamental interface for having access to almost any data. You can easily implement your own extension method and use it as a part offline. Queries. Best named Methods s spread IQ It's if the body off a method is significantly complex and long. If a critic it is short, then stick with Lambda expressions. Forget about the old feature off Anonymous methods. Careerist syntax sometimes can look more readable. However, in most cases you can work with regular method chains, classifications, offline cooperators. They can be immediately executed and deferred. Deferred can be streaming and non streaming. Yield return enables deferred execution of queries. Lee inquiries built with deferred operators will fire up on Lee at the federation. Step. Inquiries built with the deferred operators will throw exceptions on the meta data rations . Tap. Don't forget about it. Be careful with closures taken from within four and forage loops. The results may be unexpected. Be careful altering a list. You cannot mindlessly modify the list within a four or for each loop. The next short section is about data streams generation. Let's move further. 18. 01 Outline: Hi. This is engineers block from engineers spark dot com, and in this section we're going to talk about functional programming in C shop. This section is going to be very practical. The majority of types built in BCL were implemented even before extension math. It's feature was introduced, so they were implemented without any thoughts about functional programming. However, everything is in our hands and we should care about laying out the ways for functional programming on our own. This is sometimes getting a little bit tedious, but it's worth of time spent on it. Okay, so what you're going to learn in this section? This section is all about extending the types to enable functional programming and making it widely applicable. So this section covers what is functional programming, the importance off functions in functional programming, the benefits of functional programming or, in other words, why we need to understand FB related concepts. What is immune ability and how important eighties in functional programming, what is purity and how it is related to side effects? And, by the way, what are side effects? Extending the I disposable interface, allowing disposable types to be used to build gold chains extending string builder is an example, demonstrating that we can extend anything we want implementing general extensions, saying, General, I don't mean generic. Though most of general extensions are actual generic, I mean that we need to implement some extensions which allow us to compose objects which have not been compose herbal yet. So let's kick off this section by defining functional programming. 19. 02 Range Repeat Empty: with the power of link, we can generate the streams of data, for example, weaken, generate and numbers, starting with a certain number. Let's look at an example. We can run the for each loop and using the innumerable class we can call the arrange method . And starting from the five, we can generate a numbers, and we can repeat the same number several times, using the same in the lower bowl class. But using another method, the Smith. It is called a repeat. Not surprisingly, let's say we want to repeat 10 5 times, so we do that in Forage Loop and let's run the application and you can see that we generated eight numbers starting from five, and we repeated 10 5 times when and method the returns and innumerable little its name. Such method Get data, for example, and in your case, there is no elements to return. You don't have to, and you don't need to return. Now it's practice instead of that. If there is no elements, then please return and empty innumerable, using this same in memorable class and calling the empty method with a generic parameter. And in such a case, for each loop, which it raids over such a collection and them to collection. There will not be annul, a reference exception being thrown. Otherwise you'll see another reference exception in case you return null from such a method . 20. 03 Generating Random Numbers: nothing stops us from generating our own stream of data. For that, we can write a custom extension method. For example, we may want to generate a stream off a random numbers. For that. Let's create a separate class. I'll name it a random stream, and it will contain a single method stated method, which returns and innumerable of double and I'll name it generate. And the implementation will be pretty simple. Let's instance, shade. Ah, random glass and, well, true. Let's seal the return the next double through their end of class. And now we can use this class. Everything is simple. So let's run it, forage, look. And I'll use the random stream right here calling the generate method. And let's say I want to filter those numbers. I want those numbers. Which are you? Greater. Then let's see zero 0.7 and let's take the 1st 5 numbers very neat. And let's log here. These numbers very neat and beautiful. Let's run the up and you can see the 1st 5 randomly generated numbers, which exceed the 0.7. So this is how you can write your own data stream generators using link 21. 04 Conclusion: So in this section you learned that you can use the range method to generate a sequence of numbers within a specific range. You can use the repeat method to generate a sequence that contains one repeated value, and you can easily implement your own generator, such as a generator off random numbers. Using yield a return in the next section, we're going to learn about filtering, ordering and projecting data sequences. 22. 01 Outline: Hi. This is engineers block from engineers spark dot com, and in this section we're going to talk about functional programming in C shop. This section is going to be very practical. The majority of types built in BCL were implemented even before extension math. It's feature was introduced, so they were implemented without any thoughts about functional programming. However, everything is in our hands and we should care about laying out the ways for functional programming on our own. This is sometimes getting a little bit tedious, but it's worth of time spent on it. Okay, so what you're going to learn in this section? This section is all about extending the types to enable functional programming and making it widely applicable. So this section covers what is functional programming, the importance off functions in functional programming, the benefits of functional programming or, in other words, why we need to understand FB related concepts. What is immune ability and how important eighties in functional programming, what is purity and how it is related to side effects? And, by the way, what are side effects? Extending the I disposable interface, allowing disposable types to be used to build gold chains extending string builder is an example, demonstrating that we can extend anything we want implementing general extensions, saying, General, I don't mean generic. Though most of general extensions are actual generic, I mean that we need to implement some extensions which allow us to compose objects which have not been compose herbal yet. So let's kick off this section by defining functional programming. 23. 02 Select: to demonstrate you the power off link. I showed you how we can parse a CSE file using link. However, I didn't describe the operators that I used. Yeah, off course, Select under there by operators. Meaning is intuitive. However, I feel that I need to add a couple off words. Select is the operator, which allows to project a sequence of data toe another sequence of data applying conversion that you want to apply. I created here a demonstration method for a couple of examples. Let's say I have really start chess players, which I get by calling chess player Get them a list, getting the least which I created for dama purposes like Silver Player Sequels just blair dot get them a list dot to list. Select is an extremely powerful projection math at which allows to convert input in any way you want to do that. For example, we can grab all the ratings of our ratings, equals players dot select player, player dot rating and weaken. Grab all the last names. Last name, last names. We can actually transform the input dentists we like. For example, we can grab all the last names can Captain Ated with first names. I'll name it full names and I'll say here, plus whitespace plus player Dawn First name. Actually, you can perform any transforming operations on the input to get their out, but you need. You can transform the input into anonymous type. For example, I want to grab first and last names and work with the output. Yes, with an object, but without creating a separate class. For that, save our and many months type equals players dot dot select player in return you and let's lacked all the data we want to seen our anonymous type player dot first name, player dot last name like so there is a lover load off select method, which provides an index. Let's gather information for an anonymous type and save indexes as well. I can modify these coal like so, and let's say here index equals index. So you can see here that Select provides the second argument, which is off type end, and it is in iterated rings, which will start from zero. Let's run the for each loop iterating over the ratings and collection off anonymous objects . So let's running for a loop ratings rating. Angela. Let's run it for a chill loop over anonymous type, current first name and the last name like so we can run the up to ensure that everything works fine. And indeed, everything works as expected. Let's get back to our parse CV file CSE file. And if you take a look at our query where we parse a C three file, you can notice that we parse the input in the select operator passing the math, which transforms the input string. This expression is a so called method. Group C. Sharp compiler will call the Parse Feed a CIA city method passing the input string. We can re factor it toe irregular land expression black so like so this is equal to the previous version. So this is what select actually is. Basically, you can call it to transform input to output. Applying some transformation algorithm, Select always returns the same number off records as was in the input sequence. Its aims is to transform, not to filter. Filtering is all about the wear operator. Let's look at it briefly 24. 03 Where: where operator is in other operator whose aim is actually not so vague. The main idea off applying the where operator is to filter the input or, in other words, get rid off those elements, which we don't want to see in the output. Instead of looking at complex squares, let's write a couple of tree ville like I did, demonstrating the power off the select operator. Let's say we have at least off a random names. I'll copy paste. At least I prepared already if we want to process Onley those names whose length is greater than three, then we could write the following query names dot where, and you can see that where accepts a fund off string and bull. This is a delegate off type fund, which provides the input that you need Filter and bouhlel is a result, so this argument is what developers call a practical. Very often it's a mathematical lotion, which basically means that it represents a condition which determines the rule that should be applied to each element to filter them. In our case, the product. It should filter those names which are lengthier than three characters, so I can write the land expression here. Like so, Name, name dot lancs is greater than three of our filtered names. This is a very simple practical, so we don't need to expand it to a full blown form off the land expression with curly braces like so here you can see the return statement and curly braces appeared. In our case, we can make our Cold Morgan size so well, revert this change by using the indexed overload. Weakens. Keep every second element. I blame it every second, like so and let's see terrain over the resulting collections to look at the output. So let's run the app, Harold. Indeed, everything works as expected. In the first case, we have marriage on Harry and allies, and their length is greater than three. And in the second case, we got Mary Bob, Alliance and Adah every second person from the list. Okay, so let's get back to our Parsi, a city and in these complex squaring with filtered players by birth year, excluding all the players who were born before 1988. So the where operator excludes records which do not satisfy the product 25. 04 ThenBy: In one of the clearest lectures, I demonstrated how weakened Parsa ccv file how we can transform one type to another to project one type to another, using the Selic method to filter using where to order by disc ending and using pagination. Calling the take method. In this section, we learned how to filter, sort and project types using the select method. And in this case, in this lecture, I want to continue to talk about certain about ordering so to order and by more than one property. We can't just continue our method chain by calling order by twice. It won't work, so to order by after the first order by, we need to call then by So, for example, we can order by country. And for that I'll call, then by and using the Lambda. I'll pass well property we want, and we can call the PARCC demo the run method and let's look at the output and you can see the output ordered by rating and contracts. So for double ordering unit to call order by and then then by only this way, you can order by more than one property 26. 05 First, Last, Single, OrDefault: Let's look at other operators provided by Link. Let's take the same query and let's pretend that we need to take only one element in the end. So what we can do here, just ride, take one. I'll implement a separate method. And look at this when we her I take one. We steal work with the high innumerable. But why would we need to work with and innumerable if we want to work with the single item ? So Link provides several operators. For example, if we want to take the first element from a list, we can use the first method. Look at this. So, of course, if I want to take the first element right after then by we could right first instead of take 10. And, uh, the result would be, ah, a single instance of just player if we want to take the last element in the collection of Weaken, Of course, used the last method. And this methods are very neat because they except a critic, it so, for example, we can search for the first element which satisfies the falling predicate. For example, we want to find the first player from the U. S. ST like so Or the A, lest player from the US sane like so very neat. So if we were on a rap, you can see that the first player from the U. S. Was Fabian Khurana. The last one was Restless Song. The 1st 1 in the list was Carlson. The Second World wash was Christoph Duda. And what will happen if we try to find the first player from Brasilia? Let's try. But the thing is that there is no player from Brasilia. And when we run a rap, wind up with the in the valid operation exception. So the first method, as well as the last method, throws the invalid operation exception in case it can find a single at least at least one item, which satisfies the the particular condition. If we want to avoid an exception, we can call the first or default method, which will return now. In case off, there is no such elements, and the same thing concerns the last method. So we have the last or def old Methodist Well, and if I around the app, you can see that these variables equal No. If we want to take a single to find a single element, and there is only one element which satisfies a particular condition. We need to use the single method instead of first. I'll demonstrate that, and on this example he will see the difference. Heil around the up and you can see that the invalid operation exception being thrown that they says, Because if a single method will check if the only one, if there is only one item which satisfies the condition and if there is more than one item which satisfies this condition, the invalid operation exceptional will be thrown. So the single method is more strict, then first or last, and the single or default will not solve the problem. It will return now on Lee if there is no any items which satisfy the Braddock it otherwise anyway, the invalid operation exceptional the throne if there is more than one item which satisfies the condition so that single method will return an element if and only if there is a single element which satisfies the practical. So, for example, have only one player from France. And this because of that single Willer return that player who's from France and single or default will work for Brasilia. There is no maximum a shell, a graph from France and there is no players from Brazil. A. So it didn't throw an exception. So the first and last methods will throw an exception. If there are no idols which satisfy the condition, single will throw an exception if there is more than one item which satisfies the condition first or default, last or default will Ritter now in case there is no elements which satisfies the predicate and single or default, will return now as well. In case there is no items which satisfy the predicated. If there is more than one, then single or default will not save you. The invalid operation exception will be thrown. 27. 06 TakeWhile and SkipWhile: Let's look at other to filtering link methods. Let's talk about the take Wilensky Puel methods to demonstrate how to to demonstrate how take while it's keep while work. I'll write to methods, and I'll compare them with the where clause. So I'll define the take well. Method, uh, create ah list of integers like so and that First let's around the forage loop through the list filtered by where? Where I'll filter all the elements but which are greater than three. And now let's look at take well. So I'll Arana for each loop here. And I call here that take while, um, filtering all the items which are greater than three. And let's around this method here put on break point and let's run the application and look it out. So where I returned 1232 and one, all the elements which are less than three, and the difference here is that take while it takes all the elements which said it's fine. The critic it till the moment when predicated gets false, so reaching for the critical will return false and after that take, while will skip all the remaining items so it will take all the elements until the condition is true. So let's look at Skip while I train the police. Different injures. Hear us well. 123453245 And I'll run here F or H loop using where and the predicate is X is greater than three. And no, let's does this keep well, Method. I'll around a forage loop and I'll skip while X is less or equal. Three. Let's look at the output. Let's run the application and you can see that where returned 45 for five and skip while returned for 53245 Why is this so? So where filtered All the items which are less spherical than three and skip well, skipped all the elements while the product it stay true. So 123 were skipped and all the remaining items were added to the collection. Actress keep well and tick while I rarely used. But anyway, if you need to use this filtering methods, you always can use them 28. 07 SequenceEqual: to compare two collections using Link. You can use the sequence equal operator. Let's test it. So for that I'll create a separate method which hell call sequins equal, and I'll duplicate the Barson off CC file. For that, I'll cope. Ian pieced this part of code to get to duplicate toe equal collections. I'll repeat, please part of cold twice, and I'll declare the are equal variable. And I'll call the sequence equal method here to compare two collections our collections equal and they're actually equal. Okay, let's call this method from the run method to test it and let's run the code. And actually, they're not equal from the sequel sequel point off you. The thing is that by default, the sequence sickle operator will compare these collections by their reference and list and list, too point at different remember locations. That's why they're not equal to compare two collections by elements wing it to implement the high quality compare interface. And for that, let's create a separate class which I'll call players compare, which is going to implement the I compare off chess player into face. Okay, Then I'll generate the corresponding methods equal send get hash code alco peon paste The implementation I'll aerated prepared and now we can get back to our sequence, ical method and vehicle. We can pass here the instance off our compare er, which compares to players by their properties. And now we can see that now our collections are equal. So to compare two collections correctly, you need to roll out a separate method a compare which implements the I quality compare and then not to forget to pass the instance of that Compare to the sequence sickle method. 29. 08 Distinct: Another filtering operator is called Distinct, which is similar to its sequel counterpart. This filtering operator excludes all the repeated items. In other words, it includes to the resulting Sequels Onley Unique items. At first, let's look at an extremely simple example. Let's say I have a string. Hello World string pastie are equals Hello world. If I want to see all characters that have been used to build this string, I can call to char array and distinct and I'll around the forage loop here to char areas, I said and called distinct before. See console Don't right passing C. Let's look at the output drowning the app, by the way, no, right here. You line around there once again and you can see that Hello World consists off the following chars h e l o comma w R and D. This is because who have three l in the hello world string. We have two O's here, so we have here only 10 and only one l. This is how distinct works to perform de sticked against a complex type rather than against a primitive such as integer or char. You need to provide a compare er which implements of the high quality compare interface. Let's at first bring out the full dama list off chest players and then distinct them by rating. I doubt such a distinction would be a meaningful in aerial world scenario. However, it doesn't matter from the learning perspectives, so I'll command these out full dem A list off chess players like so and let's run it for each loop chess player and Doug Endemol ist player player. And now I want to demonstrate a costume distinct, a distinct with a custom. Compare. Now let's implement a custom compare, so I'll create a class here. Ah, name a distinct, distinct. These linked compare er implementing the I quality compare off just Blair. Let's implement missing members and IV parading. If ratings are equal, then return true. Otherwise, returns for return falls. By the way, we can simplify this expression by returning the equality expression right away and black. So so this implementation implies the distinction by ratings. As you can see, let's call the distant now passing our costume compare. So let's save our distinct by rating equals chess player dot get dem a list dot distinct passing you, um, how I named it distinct. Compare er like so. And let's rather for each loop over the distinct buy rating player passing that player to the console and bullets are on the app. You can see that in the first least we have Anish Geary with 2718 rating and Wesley so with the same rating. But in the second least we can see on Lianis Gary. We don't see Wesley Song It waas excluded because off our custom comparison algorithm. So this is how you can use distinct to filter collections in such a manner living on Lee unique items. 30. 09 Any, All, Contains: we have three, mainly in corporations, to determine whether specific items are in a collection or not. I'm talking about contains any and all. Let's start with the 1st 2 At first, I'll get the demo least and materialize the results immediately by calling to least so I'll save our players equals chess player dot get Demel ist dark to list. If you want to check if there is a specific item in the collection using contains, you'll have to pass. An instance often object against which you want to compare idols in the list. Apart from that, as well as in case off using sequel sequel, you'd better pass an instance often Object, which implements the I equality. Compare. Otherwise, you risk to get unexpected results. And since we have such an implementer already, I'll write a query right away. Bull contains equals. Players dot contains and let's seen Huges player. I know that there is. It's just Blair with I d equal. Six with birth year equals 1993 whose first name is Wesley. Last name. He's So he's rating equals doing a 7 18 and he's from the USA, and we need to pass the players compare, like so any is an extension method and will simply go through the collection, applying the delegate on every object. It therefore has a complexity off. Oh, off an any is more flexible. Since you can pass a delegate contains can only accept an instance of an object. So here's a simple example off using the any operator. Let's say bull players. Any player from friends not equals. There is one player from France, so any should return. True, any is more flexible than contains because you can pass it a costume predicated. But contains might be slightly faster because it doesn't need to perform a delegate on vacation. For each element, though, performance of contains depends on the collection. If you have an ordered collection, then contains might do a smart search. For example, buying a rehash balanced tree, etcetera, while with any you're basically stock within, um, aerating until you find it assuming linked objects. The last operator is called all, and it checks whether all the items in a collection satisfy a practical. I believe all the players in our Democrat Action have rating more than 2500. Let's have it or find so I'll ride Bull all equals players dot all and let's check that players are aging is greater than 2500. And finally, let's along with the results to the console undrawn. The APP contains equals contains any equals any and all equals. Let's around the up and all the queries returned. True, that's what we actually expected. So this is how contains any and all work. 31. 10 SelectMany: using the Link Select operator. We select some data, and sometimes, as a result, off using the Selic method, we end up with a collection of collections. Look at this. Let's say we have a class person which defines and name property and, ah, list off phone numbers of type string. And let's say that we have a list off persons and each person has two phone numbers. And if I call select selecting the phone numbers, then the result of such query will be a collection off lists. In this case of a collection of collections to simplify. Such a select link provides the select many operator, which makes the result of such a query plane. So look at this instead of select. I'll use select money here with the same product it I'm in passing the phone numbers proper team. But the result will be off type innumerable of string, not a collection of collections but and single, uh, united collection. And using select money, we can select data in our own fashion, so to speak, weaken selected those data which will want to select. So let's rewrite this query, selecting, um, some dating addition. Look at this So I create here and anonymous type, selecting those data, that data which I want to select. In this case, I selected the name and the phone number. So we will end up, so to speak with with a joint with joint data. Look at this Iran, the for each loop Iterating over at this collection and I send some data to the console. So let's run our method and you can see that iterating over such a collection we are iterating over a collection which joins data. So we have two full numbers here for bomb for John, for Jaffer and John for Buster. So using select many simply advise the code when the result off calling The select method is a collection of collections. So in such case, you can use Celik many to make the result off going the select method plane 32. 11 ElementAt and Counting: this lecture is very short, but I need to say about three, very simply by members called Count, Long Account and element at Let's Say we have a least off just blares before our players equals chess player dog. Get them a list dog to list like so. And to get the number off items you can call the Count Property and you'll get an integer value. Let's ST Count equals players don't count if you work with a large collection and the number off items exceeds an integer valid range, then you can call the long count method, which returns along value along long count equals players dot players don't lung gowned like so, By the way, if the collection is off innumerable type, then you can't call the count property. You'll have to call count method, And that's you may guess this is greedy operator, which will force the execution off a query so you'll have to call the count math and instead of property. If you want to get an element by index, then you can call the element at Method. If the underlying collection supports indexing, then it will work for O off one complexity. Otherwise, it. Will it rate over a collection until it reaches to the index he requested? That will happen in case off linked least, for example, So just Blair at players done element at one like So, let's longer the output count count. Long count in this case, they fire. Equal count will not throw any exceptions, by the way, the count method, which you can call on the least as well except a product it so you can count the number off items which satisfy a certain Craddock It. For example, we can count the number of players whose rating he's greater than 2700. Let's run the up and look at the results. So actually, all the players have rating greater than 2000 700. And after the first index was Fabbiano marijuana. Okay, then let's change this to 800. Let's run the up, and you can see that such players, who have only three players with the rating of that high. So this is how count, long count and element at work 33. 12 Conclusion: Congratulations. You've finished another section, and in this section you learned that select operator allows to project a sequence of data off one type into another sequence of data off another type. You can order by ascending and descending, calling the order by or order by descending operators. If you need toe order by more than one property, then use than by operator first, last and single allowed to search for a particular element passing a product. It single is more streaked, since it allows having only one item, which satisfies the radical first or default last or default, single or default allow to avoid exceptions being thrown. Use it if you're okay with having now as a result off your query. Take while Inskeep, while are actually rarely used. Filtering operators take while takes older items until a predicate turns falls for the first time. It will continue to reiterate over a collection after that on the country, Skip Wiles keeps all the items until a predicated turns faults and all the remaining items will be added to the resulting collection Any and contains allow to know if a collection contains a specific item any except a critic. It contains, except an instance often object. The all operator returns true only if all the items satisfy the Braddock. It sequence equal will compare sequences by references by default. If you need to compare collections by elements, then you have to provide an implementation off the equality. Compare interface. Select many is beneficial. When regular select returns a collection off collections select many flattens the result off such a query. Joining the elements That was an interesting section. The next one is important as well, and it is dedicated to joining grouping and aggregating operations. Let's move on. 34. 01 Outline: Hi. This is engineers block from engineers spark dot com, and in this section we're going to talk about functional programming in C shop. This section is going to be very practical. The majority of types built in BCL were implemented even before extension math. It's feature was introduced, so they were implemented without any thoughts about functional programming. However, everything is in our hands and we should care about laying out the ways for functional programming on our own. This is sometimes getting a little bit tedious, but it's worth of time spent on it. Okay, so what you're going to learn in this section? This section is all about extending the types to enable functional programming and making it widely applicable. So this section covers what is functional programming, the importance off functions in functional programming, the benefits of functional programming or, in other words, why we need to understand FB related concepts. What is immune ability and how important eighties in functional programming, what is purity and how it is related to side effects? And, by the way, what are side effects? Extending the I disposable interface, allowing disposable types to be used to build gold chains extending string builder is an example, demonstrating that we can extend anything we want implementing general extensions, saying, General, I don't mean generic. Though most of general extensions are actual generic, I mean that we need to implement some extensions which allow us to compose objects which have not been compose herbal yet. So let's kick off this section by defining functional programming. 35. 02 Join: link provides the join up there. Adrian, which is an Anna lock off the joint in sequel to test to the joint method. At first, I'll create a class tournament, which will contain information about the tournaments in which chess players participated in . For that, I'll cope in pace to the code, which had already prepared It contains several properties, and it exposes the get demo stats method. Which returns, um, some, um, list with the corresponding data for demo purposes. Let's say that I have to collections a collection off players and the collection of tournaments, and I want to join them by player i d. For gathering data from Bach elections. So yep, to end up with a joint date for that, I'll expose um, two methods. I'll copy in based a piece of gold, which, um, parses CSE file. And let's say that we have a list of tournaments. Uh, I called the get Demas stats method and let's join them for that. I'll say, let's join and by the way, our nameless two players. So we need to pass the second collection to join, and we need to pass the property for joining the key for joining. So we select I d from player and we select player i d from tournament. These are I d symbolical actions, the keys. And after that I want to create an anonymous, um, class selecting data, which I want to seen the end. So I select last name. I select select rating the state I select from player and I want to select, um, title from the tournament and taken place from the tournament and country. So, in fact, all the data from both collections and now we can run a forage loop iterating over these joint collection and let's right some data to console. Let's try in the last name. That player took that place. It a particular tournament. And that player has the following rating. Very neat. So I'll move the tournament class into a separate file. And now let's run. They joined them. A method passing this file location is seriously file and let's called a demo method from the main method and you can see that went up with a joint and we see the output of these joint data which displays players and tournaments those players participated in 36. 03 GroupBy: link allows to group the items, for example, weaken group, the chess players by countries. How to do that? Let's look at an example. So let's say I have the same queer here, but I want to continue the squaring grouping the players by country. For that, I'll call group by passing the property by which I want to group the players by and let's see. After that I want to order them by. You can see that the result off Group by is of Type I innumerable off I grouping and let's say I want to order by descending the grouping by the key and the key off the grouping will be the country. So this case, I, I order them by key. It means by country by descending Let's run the for each loop iterating over the players and that's send some data to console lugging the player, and we should run an inner forage loop to reiterate over a country over players inside the country. So let's call the group by demo from the Dem a method, and you can see here that Cara Wana and Wesley so leaving you say correction and department she live in Russia do Dane talent in with their land, Geary and so on and so on. Karlsen, Norway. And by the way, we can modify our Joel querian using the group by method. For example, let's get back to the, um joined Emma. I joined here players and tournaments, and after that ah, maybe I want to group they them by country and order by taken taken places. I mean group by countries in which tournaments have been run. So I group them by country and then called select money to get a plane a result and inside select many I ordered by the grouping by taking place. So now I can around a forage loop and send some data to console weaken coping the same output here. So let's get back to the demo method. And let's uncommon the join down a method. Yeah, let's separate these queries somehow to see where um, a particular query goes. So you can see here that Carlson marijuana taken took first and second place is a tournament. One they have The following rating was list. So took the third place and sole and soul. So we end up with a plane result ordering by taking places at tournaments, preliminary groping by countries so you can combine and different link operators to achieve those results you need to achieve. So. Link has an enormous power concerning different possibilities allowed by different combinations off link operators. But of course you need to practice a little bit all those operators to harness all the bar off link. 37. 04 GroupJoin: What if I want to join two collections and group them in one shot for that link provides the group joined Method, for example. Let's say I want to group players by tournaments they participated in and actually a numerical create case. It would be quite complicated because both players and tournaments collections are to de normalize. So in our case, it would be easier to join players in tournaments. Um, by I d. And after that, using the group by group, all that stuff by tournament titles. Okay, then I'll create a separate demonstration method. I'll call it Group joined Demo. And let's say that Do we have Ellie stuff teams? Let's create the team class. Let's feel it by properties. It exposes the name off a team and of the country for which of that team plays. So two properties off string type. And let's create another class which represents a player, and it defines two properties of the name and the team. Let's feel to the teams and players lists actually have already prepared to lists here are they and let's test to the group join method, so I'll call group joined on the team's collection past the players collection and let's join them by the team name. For that, I'll select the name property from the team, um class and the team property in case off the player class. And after that I want to group players by teams. And for that I need to call group join exactly on the team's collection, not vice versa, not on the players, exactly on the teams. In this case, we will group players by teams, so the sequence off collections is relevant in this case and I'll select told the data. I want to see in the result some the name, country and players. So now we can just Rana for Schlupp Iterating over the result at the top level will have a team. So let's say that players in a particular team and after that run an inner forage loop iterating over Blair's. So players are grouped by teams and that's called this method instead of during Dima. But that's it and you can see that in Bavaria. The rubber band plays in Barcelona, Messi and Neymar and so on. So this is how group join works 38. 05 Zip: link defines a relatively rare used operator named Zip that operator allows to join two collections string by string without using a key. Actually, I haven't ever used these eep operator on my own practice, but Link provides that this operator and maybe one day you'll face the situation when you need to use that operator. So let's demonstrate how to use their zip operator. For that, I'll create a separate method. I'll name it Zip demo. And let's say that we have to lists the list of teams and players and let's supply the ZIP method for of these two, uh, collections. And let's look at the result. In this case, I'll say players dot zip, passing the collection of teams and then let's construct an anonymous type name equals player. That name was selecting and data which we want to and team equals team not name, and we take country from Team a swell. And now let's run the forage loop iterating over the result on Let's send some data to consult. Let's log the name, team and country. Let's call the Zip demo from here, and after that, let's run the application and you can see here the results off this joint. So in this case, we join the list these lease without using a key, just selecting with the data we want to select. For example, we get here the name off a team from the team, um class, not from player. So this is how Zip works it allows to cat, so to speak. Collections string by strict string without using specific key. 39. 06 Min, Max, Sum, Average: link defines some other very helpful aggregation methods, such as mean Max summoned average. So let's quickly look at how to use them. So it's first I'll define in your state of method, which I'll call. I mean Max some average, and I'll call it from their own method right away. And let's say I have here a query for a CS file with Parse it and we end up with a list. And if I want to find a player with a minimum writing, then I can use them mean method like this. I'll say console ride, lying right away and say here the lowest rating in top 10 and I'll put the query right away , right here, really stuck mean, which accepts the bread IQ it. And in this case, I want to search for the lost rating. So I'll pass the aerating property here. And if I want to find a player with a maximum rating, then I can use the, uh, max method. And if I want to calculate the average rating off the top 10 players, then I can use the average method besting the same property. Actually, there are no properties for which it's illogical to calculate some. So I'll just create here, at least for demonstration purposes and list a list of integers and now the best here. 123 And after that, I'll calculate the sum off these values. So I'll say here the some off numbers in data equals two data dot some. But it's a simplest form off this some method without any predicates. So let's run replication. Oops. Sorry. Let's, uh, call, uh, the Parsis freedom around from Maine. So the lowest rating in top 10 equals 2740. Carlson has the maximum rating and ever choose 2784 and the some off 12 and three equals 66 so everything works fine. 40. 07 Concat and Union: apart from the joint operator, we have four other operators which represent a form of joint. These are Can Cat Union intersect and accept operators? Let's start with concurred, and Union Cat is the most straightforward operator among those I mentioned. What it does is that it just adds items from one collection to another without any conditions and returns a newly created instance. If I'm vulnerable, let's say that we have two lists off products. I'll copy and paste to list. I have prepared already and to check How can cat works? Let's run a forage loop right away for each products one dot com cat We've products to of our All right, um, console dog. Right. All right, um, separating by comma. So I just can cat products one and products to Let's run the happened. Look it out. Yes, you can see now we have seven items. This is because four items from products to were added to three items from products. One you could say that you could just use at the range adding items from products to two products one and you'd be right. Actually, you could do that. However, the semantics off these two ways is very different. The thing is that at the range modifies a collection while come Cat does not. Can CAT works with ing innumerable, while ed range can be unsupported in certain collections. So this is how you can use Come cat. Let's move further and try to call. The union Operator Union is similar to Can Cap, but it leaves only unique items. For example, if we union these two lists, you'll see milk only once in the resulting collection, while in case of a plan can Cat you'd see two milks, so expect that we will see six products in the resulting collection after applying union. Let's test it. We're testing union in L around four ish loop products one dot union products to lugging the item. Let's run the happened Look it out and indeed you can see only six items have been printed out, so the second milk was excluded. To exclude items. Union has to compare items. If we don't provide any algorithm off comparing items, union will try to use comparing algorithm that can be applied by default. If we want to union to collections, applying our own comparing algorithm, then we should provide an instance often object, which implements the I quality compare interface. For example. In this case, I want to treat items equal If they're different only by casing, we'll have to butters. One is better from a lower case letter and another butter from the uppercase letter. Logically, these are the same products, so it would be also logical to leave only one of them applying union. If I want to achieve that, I need to implement an object which inherits from the equality. Compare. I'll create a class I'll call it products. Compare, which implements the equality. Compare off string and I'll treed. Strings s equal if they're different only by casing, so I'll call string equals passing X. Why and the comparison algorithm? Ordina League lore case Because I want to glower casing return object dad to upper don't get hash code since I am ignoring the case. Okay, our implementation ignores letters casing and let's pass an instance of products compared to the union method. I'll Akopian face to this. I'll say here, Custom Union and let's best here as a second argument. Our new products compare Now let's run the up and look at the results, and you can see that now. We ended up with only five items. The second butter was excluded from the output. So this is how can cat and union work? 41. 08 Intersect and Except: another two operators I mentioned are called Intersect and accept. Let's say we have the same two lists off products intersect. Operator is used to retrieve the common records from both collections. So in our case, comparing items by default, we have only one common item, which is milk. So applying intersect without passing products. Compare er as the argument. I expect to get a single item in the resulting collection, except it returns items which exist in the first collection, but at the same time which don't exist in the second collection. Comparing items by default, this operator will exclude milk since it exists in the second collection. The remaining items do not exist in the second collection, so I expect to see two items in the resulting collection. Let's right to calls and iterating over resulting collections of our Intersect equals products. One dot intersect products to let's from the up and you can see that in the first case, only milk was included to the result, and in the second case, milk was excluded and remaining items from the first collection included butter and soda. Everything works as expected. If I pass in. Both cases are custom product compare, then results will be different. Intersect will include barter in addition to milk, since butter from the lower case and butter from the upper case will be treated as equal strings except will exclude barter by the same reason. So as a result, only one item soldier will be included to the resulting collection. Let's pass our custom, compare and drawn the app and look at the results so I'll pass here. New products compare, and I will pass it here. Us. Well, let's run the up. Indeed, everything works as expected. So this is how you can use intersect and accept link operators in your own practice. 42. 09 Conclusion: Congratulations. You're on the right wing. 1/2 off course you already learned in this section. You learned how to join collections using the joint method, which is very similar to the joint operator and sequel. So if you have a key for joining collections and go ahead and use it, how to group collections group by Accepts a property by which you want to Group two collections group by Returns and I innumerable of my groupings basically calling Group by. You'll end up with a one to many data relationship, so each single key corresponds to many values. How to use a group joint for groping and joining in a single shot group joined just simplifies grouping and joining, which can be done in one shot. Zip is joined without relying on a key for joining so calling Zip. You decide which data to including to a newly created joint collection. I mean Max allowed to provide a practical for searching specific minimums and maximums. Summoned average, not surprisingly, calculates some and average okay in the next section, we're going to learn about conversions 43. 01 Outline: Hi. This is engineers block from engineers spark dot com, and in this section we're going to talk about functional programming in C shop. This section is going to be very practical. The majority of types built in BCL were implemented even before extension math. It's feature was introduced, so they were implemented without any thoughts about functional programming. However, everything is in our hands and we should care about laying out the ways for functional programming on our own. This is sometimes getting a little bit tedious, but it's worth of time spent on it. Okay, so what you're going to learn in this section? This section is all about extending the types to enable functional programming and making it widely applicable. So this section covers what is functional programming, the importance off functions in functional programming, the benefits of functional programming or, in other words, why we need to understand FB related concepts. What is immune ability and how important eighties in functional programming, what is purity and how it is related to side effects? And, by the way, what are side effects? Extending the I disposable interface, allowing disposable types to be used to build gold chains extending string builder is an example, demonstrating that we can extend anything we want implementing general extensions, saying, General, I don't mean generic. Though most of general extensions are actual generic, I mean that we need to implement some extensions which allow us to compose objects which have not been compose herbal yet. So let's kick off this section by defining functional programming. 44. 02 OfTypeCast: link provides two methods for casting types. Toe innumerable from another collection in Link off type, which returns only the elements of Type X and cast, which will try to cast told elements into Type X. And if some of them are not from this type, so they're not convertible, you'll gather the invalid cast exception, and so off type will not throw such an exception. It will try to cast Onley those objects, which are cast a ball salutes. Let's look at the demonstration I created here. Yeah, method. Let's say that we have in the ray off objects and let's fill it. The first element is off type string, and the second element is of type integer. I'll expend the try block, and I'll test the cast method off string. And let's call here that to air a method, make sure that we can call here need to least there's no difference. So, I think, is that the cast method will not throw an exception if we are not going to materialize the results of this query immediately. Since we don't have here for each loop and I'm not going to run if a ritual up, so that's why I call to array explicitly, and I'll catch the invalid cast exception here. And let's test here the off type method off string and, yeah, let's let's Iran the for each loop here. Since I know that off type will not fail, let's throw on the up and you can see that in first case, the invalid cast exception was thrown. And in the second case, the first item was converted to yes, drink and you concede finally. 45. 03 ToArray, ToList, ToDictionary, ToLookup: link allows not only to cast types from within collections, but it allows to, um, convert different types of collections to other, uh, types of collections. For example, we have to list to Iran to look up methods and look, it's look at how we can use them. And let's start with a simple one. So I'll create a stated committed, which I'll call to arraign to least So we will look here at to Iran, to least within this method. At first, I'll get them a list from just player, which is off innumerable of just player type. If I want to get the least instead of final memorable, then I can call to list and by the way to least can be called on an array. It will work a swell. So wind up here with the least off just Blair. And if I want to end up with an array, I can call the two array method, and in such a case, we end up here with an array off just blares. And as I said, I can convert in array to a list just going to list on in every it will work. Let's look at it out, but, um, running a forage loop. Iterating over players one. Yeah, let's send some data here to console. Let's say player name, last name here and let's do the same iterating over in the ray just to see that they're equal. And you can see that both lists contain the same data. But we reiterate over different types of collections and we have at our disposal the two dictionary Method Tool Um, convert a collection to a dictionary where um exists a unique key and s. You might know dictionaries are very effective, Um, from the point of view off accessing their elements. So they're very performance in accessing. So here I'll create to dictionary method, get here Demel ist and, for example, we may want to convert the collection of players to a dictionary using their I. D's as a key. And after that we could use the dictionary in an efficient manner since, as I said, dictionaries very efficient when we talk about the performance off accessing that collection, so dictionaries very performance. So you need to call the two dictionary method and pass a property, uh, which will serve as a key, and we around the for Rachel appear of passing some data here. Uh, let's see. Uh, a key. A key here is an I D. And let's look the last name A swell. Actually. I had to tweak the least returned by the get them a list because ideas were not presented there. So I just added them manually. It's a Demel ist, so I don't pay attention to it. Okay, so I'll run the up now, and you can see here that ideas are unique and the last names off chess players. So this is how you can use the two dictionary method to convert a collection. If you can provide a unique key off course, Link provides to look up method, so to look up. It's a cross between a lie grouping returned by the group by method and the dictionary, and it lets you group items together by a key and then exes them vie that key in an efficient manner rather than just by rather than just iterating over them all, which is what group violence you do. So you'll gain some, um, benefits in performance. So, for example, you could take a load off, don't know taps and build a look up by name space, and then you can get to all the types in a particular name. Space access very easily. And here's what we can do here with to look up method. We look at this. So let's select some types which reciting different assemblies and then tell get to the array of types. So, uh, I'll, um, say here list generic one string type off, innumerable and type of XML aerator You'll see in a second what I'm going to do. And after that I'll get all the types off those assemblies which contain these types. I'm in least string innumerable and expel aerator. And for that no, um, say simple types don't select and, um, Iterating over these times I can query the assemble ists, and I'll call select many to end up with them plain collection, selecting all the types from those assemblies. Still Nike. So now now I can group all the types by assemblies and for that I'll use their I look up off string and time so all types dot to look up passing the name space because we're going to group by name spaces, all the types and now we can, um, it rate over the blue cop. Like so. Oh. Yep. So here I want to access some kind of name space. In this case, let's say system. So we're going to reiterate over all the types in the system name space, and I'll get the full name off a type and the name all for the assembly. Yeah. So this is how you can observe all the types in the system named Space in different assembles. Ah, having indexed access, which is very efficient, of course. 46. 04 Pitfalls of Conversion: in this lecture, you'll see some old things that happened to conversions between types using link old at the first sight. Indeed, there is always a correct explanation. Since we're a tech guys, we're not talking about philosophy or economics. Okay, then let's look at an example. We have a function here which defines the list of integers. Then we have for expressions, which try to convert the least off integers to the list of doubles. The first expression relies on extension method you can see below. The second expression uses the standard cast method, the other to rely on the sequel like syntax to perform the conversion. The question is, which of these expressions work fine and waged a lot? Write your answer and get back to look at the reality. - Before running the code, I'll wrap expressions into try cage blocks. Now I'll run the code, and the first expression fails. Why? The thing is, that runtime item is of type object, and we can't cast it to double the invalid cast exceptional the throne. The second expression fails because of the same reason. Cast method works exactly the same as the previously called Convert Method. They're roughly the same. The first sequel like expression is the same as the previous cast method. So with throws, the last expression deliberately casts each item to double explicitly. What allows all the items to be converted properly cast in a query always solves the problem. In such circumstances, remember that generics can't see conversion operators, boxing reference and malleable conversions. The first way to avoid the problem, as you have already seen, is to cast in a query. However, there is another way. Actually, we can fix our first expression for that we should change the convert method. What do you think we can do here to solve the problem? - Object is a pretty stupid type. It is the source off our problems here. We can leverage the power off dynamic typing. Starting from the dot net for Dynamic allows compiler to see the underlying type at run time so we can change the object. Type two dynamic and everything will work fine. If you are not aware of dynamic typing Google for it and read about the dlr in dot net 47. 05 Conclusion: congratulations. You reach the end of the section, and in this section you learned that off type will convert only those times, which can actually be converted into requested type, while cast will throw an invalid cast exception if it stumbles upon an element which cannot be converted to list onto array are straightforward and their aim is clear. To list, converts a collection into a list and tour a color vertical action into an array. The dictionary allows to convert a collection into a dictionary, but you have to provide a unique key. To look up is a cross between A and I grouping and the dictionary. It lets you group items together by a key, but then access them via that key in an efficient manner. S innumerable is usually used for converting tonight innumerable from Mike, wearable and esque, wearable to convert when IAC wearable from I innumerable M generics cannot see conversion operators, boxing reference and malleable conversions. If you need to cast, say innumerable off integers to innumerable of doubles, try to cast within s elect expression explicitly 48. 01 Outline: Hi. This is engineers block from engineers spark dot com, and in this section we're going to talk about functional programming in C shop. This section is going to be very practical. The majority of types built in BCL were implemented even before extension math. It's feature was introduced, so they were implemented without any thoughts about functional programming. However, everything is in our hands and we should care about laying out the ways for functional programming on our own. This is sometimes getting a little bit tedious, but it's worth of time spent on it. Okay, so what you're going to learn in this section? This section is all about extending the types to enable functional programming and making it widely applicable. So this section covers what is functional programming, the importance off functions in functional programming, the benefits of functional programming or, in other words, why we need to understand FB related concepts. What is immune ability and how important eighties in functional programming, what is purity and how it is related to side effects? And, by the way, what are side effects? Extending the I disposable interface, allowing disposable types to be used to build gold chains extending string builder is an example, demonstrating that we can extend anything we want implementing general extensions, saying, General, I don't mean generic. Though most of general extensions are actual generic, I mean that we need to implement some extensions which allow us to compose objects which have not been compose herbal yet. So let's kick off this section by defining functional programming. 49. 02 XML Document Structure: in this section, we will be focused on types published in this system dot xml that link assembly which is included by default in tow. Almost all the projects you can create in visual studio the system dot xml That link defines several times prefixed by X. For example, to read and create XML documents, you should use the X document Class Ex document is a container for different XML elements. Basically, any XML document consists off a declaration which is represented by X Declaration class. Any XML document consists off at least one top level element. All the elements in XML are represented by the X Element class, which is hierarchical in its nature since it can contain many ex elements. Any X element can contain multiple attributes which are represented by the ex Attribute class commence in XML I, represented by the ex common Class X Element X Attribute index comment are derived from X node, which provides the basic a p I. Let's look at how to use these classes to generate an XML document in the next lecture. After that, you'll see how to read an XML document and how to use some tricks to avoid common problems . By the way, you don't have to set up the X Declaration for each X document. If you ignore setting up X Declaration ex document will generate an X Declaration by default. 50. 03 Creating XML from a Collection: Let's look at how we can convert data from Cicely file to XML. Uh, at first we need to parse a C C file to get a collection of data. I'll coping based a part of code here, actually a line of God where we get on the path to a file to assess the file and we can parse that file right now. You can read all lines from that CFC file it first, then when you just keep the first line because it contains the columns of the names of the columns. And then we will project of the, uh, records to chase Blair and materialize the results, calling the two least right away. And now to convert to these collection to an XML document, we I need to at first create I am an instance off X document. Let's do that. And the top node will be the players note. And each note is represented by an ex element instance. And as I said, Let's pass here the players a string literal. And now we need to feel these note by players for that, I'll around the for each loop iterating over their records, and now we need to construct the inner elements off the players node. So let's create the, uh, player node. I'll call it player. It's off X element instances. Well, and now let's create all the elements which feel with the player. Uh, so a player consists off i d and writing and rating and, uh, the date of birth and country and the last name soil fix here. Everything yes, needed the birth year and all the remaining properties so the player can see stuff all these, uh, properties. And now we need to add all these elements. Two of the players note, like so using the ad method. So let's adhere Name writing, birth your country first name, last name. And finally, let's add the player node to the players note. And and then, after the for each loop, wing in tow ad, the players note to the document. For that, I call add on the document instance, and finally we need to save the eggs document in a file. I'll name it just blares dot xml, for example, and let's run rap it finished the execution and let's look at but the file Let's look inside. You can see here are XML file in note, but plus plus it looks like this. So players note contains Mahaney player nodes. And actually, we have a bug here. All the inner elements off the player node are cold ID's. It's a result of copy pasting. I'll fix everything quickly just to rename it the strong liberals, and everything will be fine. Let's River on the application. It finished the execution. Let's look at the result once again. Here it is. And you can see here the right elements inside the player nodes. So this is how you can transform a collection, any collection into an XML document. 51. 04 Refactoring Code: I believe you'll agree with me that this code, which transforms a collection into an XML file, looks quite ugly. It's quite complicated. It's long and actually we can simplify it. So at first we can simplify it, using X attributes and using the power of Flink. So let's refectory. At first. Let's make all these ex elements s X attributes and X element allows to build nesting. So what does it mean? So instead of closing the X element here, I can expand it, Um right, coma and nest. The axe attributes. So I'll name it I d and pass the corresponding value. And let's repeat this step to replace oldest X elements bikes except tributes. I'll do this in this slick way, like so, So we can remove all these lines now. And you can see that even now, the code his cleaner and simpler and by the way, we can proceed to refectory it. So instead, off using the for each loop, we can expand the top level X element and using the power off link, we can write the select operator and project all the records in tow. Ex elements with ex attributes. So everything is done here and we can cope in based on this piece of code. And now we can remove the for each loop now that the goat is march much cleaner and much more understand abodes much more concise and reliable. So, following this kind of free factoring, you can transform any collection into an XML document in an easy way. So let's run the application and look it the results. So I'll open the Expo file made the way this file weights is twice Ah, lists, then the first variant. And here's how our XML file looks like instead of X element nesting. We have attributes in each player, so we have a more concise gold as well a s'more concise XML. 52. 05 Reading XML: you've seen how you can transform at data from a collection into an XML file. Let's look at how to read an XML file, so I'll declare, read XML function. And at first we need to read the XML data using the X document class, calling their load method and pay attention that they load method loads into memory, the whole XML file And in case you need toe work with large external files, most likely you have to refrain from using the next document with its load file. And instead of that work with an old AP I off XML, a reader which allows toe work with XML as a stream of data. In this case, I just pass it in, ah, a name off the XML file into the load method. And now let's construct a query. So at first I'll call the element method instead of elements because the top level players is single in our case and in its turn, the players note contains many elements. So after that, I call the elements method, passing the player name because players contains mania. Players. Yeah, and, uh, I'll continue the yeah query by calling They wear method and I'll cast the X attribute, which is called rating to an integer, and I'll compare it to 2700 extent tribute over loads casting two different types so we don't have to right here in dot parse So we can explicitly cast an ex attribute to an integer, and if it is possible, then it will work fine. And after that, I want to select of the your last names off players whose rating is more than is greater than 2700 finally working around for each loop. Iterating over this query. So let's log someday to here by writing to console. And here's the question. Is everything fine with our aquarium theoretical? Everything is fine, but it can fail in many places. For example, if Dr Element players returns now than the elements will throw the null reference exception . To avoid this problem, we can apply the null propagation operator, which appeared in SI shop sinks, which allows to avoid another reference exceptions. So if dot dot element doctor element returns now, all the remaining calls will be skipped, and for now, the forage loop can throw a little reference exception because we can't reiterate over a collection which is equal to know it will lead to another reference exception. And so we need to improve our aquarium further. In the majority of cases, we don't need to return. No, in case we expect a collection. As a result, it's better to return and empty collection. And in this case, I'll use the no coalescing operator. So if they result, if a query is no, it will return and into collection, which will solve the problem off no reference exception that can potentially be thrown from the forest loop. And in case someone will change the last name to less name to, for example, the access to the Value Property will throw with another reference exception. And we can use the no propagation operator in this case, a swell. So now our query will not throw over the another reference exception anywhere. So now it's very reliable. Let's run the app and look at the results and you conceal the players. Was rating is greater than 2700. That's great if I change the name off note around the up. Our rap doesn't crash. We end up with an empty and collection. And the same thing will happen if we if we will introduce a mistake in other string liberals like list, last name or rating. So using the power of C Sharp six using null propagation, all coalescing operators and so on, you can build very reliable lean queries. 53. 06 Conclusion: I could dedicate a separate course toe entity framework. Since it's a huge topic, however, we briefly looked at how to use linked to entities you learned that you can use linked to insert data to a data basis usual that you can use linked to retrieve data from a database s you did with the regular objects. But at the same time linked to entities hide some people, such as a lack off support off particular link operators and the necessity to understand the peculiarities of transforming link queries to sequel queries. Insured somebody inquiries can be transformed into plain sequel and execute on the server in a very inefficient way. So you always have to track down all the performance related issues that can arise here and there from time to time. Be careful with that. 54. 01 Outline: Hi. This is engineers block from engineers spark dot com, and in this section we're going to talk about functional programming in C shop. This section is going to be very practical. The majority of types built in BCL were implemented even before extension math. It's feature was introduced, so they were implemented without any thoughts about functional programming. However, everything is in our hands and we should care about laying out the ways for functional programming on our own. This is sometimes getting a little bit tedious, but it's worth of time spent on it. Okay, so what you're going to learn in this section? This section is all about extending the types to enable functional programming and making it widely applicable. So this section covers what is functional programming, the importance off functions in functional programming, the benefits of functional programming or, in other words, why we need to understand FB related concepts. What is immune ability and how important eighties in functional programming, what is purity and how it is related to side effects? And, by the way, what are side effects? Extending the I disposable interface, allowing disposable types to be used to build gold chains extending string builder is an example, demonstrating that we can extend anything we want implementing general extensions, saying, General, I don't mean generic. Though most of general extensions are actual generic, I mean that we need to implement some extensions which allow us to compose objects which have not been compose herbal yet. So let's kick off this section by defining functional programming. 55. 02 Preparing the Project: I'm planning to demonstrate you how to use the entity framework with Link. Throw the sequel server to be a mess. I'll I'm going to work with a local, maybe a mass with a local Debbie. And, of course, you'll have to install the sequel server on your machine. I haven't stole the sequel Server 2017 Developer Edition and before we're going to write a couple of queries for inserting and reading data, let's do some actions. At first we're going to work with the chess player type. And actually, we don't have to do anything with the chess player glass, since Entity Framework works with automatically implemented properties out of the box without any attributes applied. So we just can, uh, stick to the current implementation off the chess player. So the first thing I'm going to do is that I'll open the server Explorer and test to the connection to local DB MSs card, local to be and disconnection succeeded. Unfortunately, you can't see the button off connection because I am recording this lecture in 7 20 p while my screen is 10. 80 p and this window is not recyclable. Unfortunately, so there is a there is a test button and the connection with my sickle server, uh, goes well. So the first thing I'm going to do is that I'm going to publish class we shall cultures player to be, And I'll inherited it from the debate context, Uh, which is the type from the entity framework. And to use this type, we need to reference the entity framework package. So I will go to a new package manager and then stole the entity framework with the 6.2 version. I stole it and import the type. And I'm going to work with a single set of data with with a list of chess players and in entity framework to publish a set off data union, too. Uh, declare a debis set off chest Blair's, and this is going to be a property which is named just blares. And for initializing the database, I'll call the database sit initialize er passing a stretcher gene, which is called drop create database. If model changes. Ah, the, uh, I would not recommend to use this strategy in production just simplifies my life for the DeMott purposes. And let's go to methods. Insert date and query data it was January. These methods and that's it for this lecture. Let's look at how to insert and query data working with into the framework in the next lecture. 56. 03 Inserting & Reading: in the previous lecture have set up everything we need to to insert data and query data from a database. And let's start with inserting some data. So I'll Coby this line of code where I get the birth to a file which contains which points to the CCT file. Let's parse it. Riddle lines from a CSE file, then helps keep the first troll and then project all the lines to chest. Blair's using the parsing method and materialize A with the results, um, calling the greedy operator to list after that, how instead, she ate the chess player Debbie. And if there are no any records at this point, let's add the chess Blair's calling the ad arrange method and passing the records. And finally, we need to call the safe changes method to actually insert all the data. And after that, we can query the newly inserted data for that again, let's again instance, shaded Just Blair to be and a let's, um, a sign console right lying to database log to log the sequel queries, which will be performed by Sequel Server, which will be created by Entity Framework. And let's right the query for that lads axes the chess players to be set and and filter the players whose rating is greater than 2700 and order them by descending Buy rating and let's run a flourish. Loop iterating over the query and look some data to the console. Let's see Clear list name and his rating. So it's check how the cord cold works. Let's around the up So the data is is getting inserted. The data was inserted and they were queried. And by the way, you can see how they were created through this select, which was generated by the entity framework. Exactly. This query was performed and SQL Server. So this is how long you can work with entity framework using the power off link framework. 57. 04 Pitfalls of LINQ to Entities: we talked about how to insert and read some data using Link and let's talk about what Pete Fels are hidden by Entity, framework and link. So at first, let's instant shade and instance off, Just player to be and the first beautiful is in correct sequence off methods being called. I'm talking about link methods. So I'm writing here query filtering players buy rating, and after that I order them by descending by writing. And if I call to least and then I call take one or take two or take 10 I would say that the square area will be very inefficient because to materialize all their records when we called to least sequel will select all the records, of course, which satisfy the where clause. But before taking only 10 records, each will select all their records. That's why it will be very inefficient. And to avoid thes, we need to re order the operation calling at first take 10 and only after that call to list . And in such a case, sequel will generate a very efficient query which will use pagination, and it will read only the 10 records and after that. But you realize only those 10 records. It will not select all the records which satisfy the where clause and another problem his when we use unsupported operators. Unfortunately, an entity framework is not capital off transforming all the possible link operators. For example, if we're going to try to ride the following, uh, query filtering by writing, then ordered by descending, and then let's say we want to check If, um, that collection contains just player in this case, I pass it just player created by default without any prepper tip properties being said. But it doesn't matter, because anyway, entity Framework will throw an exception. I'll attach a link to this lecture leads to a Web page where you'll see those the Rangers, which are im supported by entity framework. So using those operators, you'll face an exception thrown by entity framework. I'll command town these part off gold and I'll demonstrating that the exception really will be thrown. So we're on the up and you can see that we face here the not supported exception because because that they contains Methodism supported by entity frame. So be careful with using particular link operators when you work with entity framework, so working with linked to entities. You have to understand which operators are supported and which are not. And by the way to use linked to entities, it would be better to understand how particular operators get transformed into sequel queries to use it efficiently and avoid common people's related to extreme degradation. Off performance off Queries Ran on Sequel Server 58. 05 Expressions, AsEnumerable and AsQueryable: link provides to query architectures, local queries for local collections and interpreted queries for remote data sources. We've been working so far with local queries for local collections which implement I innumerable, all the methods you call on innumerable, such as wear and order by they will be called US. Methods implemented by the innumerable class interpreted queries are descriptive. They work against collections which implement like wearable and all the methods you call on an equal arable, such as wearing on order by. They will be translated in taqueria below operators, which produced expression trees that are going to be interpreted at their own time. There are two main parts off link framework which provide queries based on the Ike wearable . These are linked to sequel and linked to entities. In this course, we're going to briefly look at link to entities toe, understand why we might need to use s invulnerable and ask variable. You need to understand other facts. For now, you need to understand that other domains collections, such as those for accessing a database could choose to implement their own sequence type and operators. Ordinarily, when calling a query operator on a collection off one off those types. A collection specific operator would be called the S. Innumerable operator allows the input sequence to be cast as a normal, invulnerable off T sequence, allowing a standard queer operator method to be called to explain. On an example. Let's get back to the previous example where recalled contains accessing a database of I linked to entities. Look at this code in the people's method. Carefully here. Instant Shade A chess player DB Class, which contains the chess players property off type DB sent. Here it is the DB set type implements of the EIC wearable interface. I queria ble basically provides the same set of quitter operators here. You can see that I call the wear method than Eichel ordered by descending and finally contains Look at the signature of these where method you can see that this method returns and I quit arable and accept an expression. The first fact here is that we work with an acquire, a bill collection and the second fact that instead of taking a regular funk, it takes an expression of funk. Why is that and what is that? The thing is that linked to sequel and linked to entities have to translate our queries into sequel, and they do that in the round time. So what is an expression tree? Look at this. I'll create a separate method. Let's sale going dama expression. You should remember that the lecture about Lambda Us and Anonymous functions Let's they're called the Lambda Expressions. Let's create one. I'll create fuck off int off end off end like so I'll call it Ad equals. It takes two integers and returns and integer c Sharp compiler will expand the Lambda, transforming it into a method. This delegate is easily invoke. Herbal this in other regular method so we can call it like this. Of our result equals add passing one and two expecting three is now. Yep, like so. And let's and let's right to the console, the string representation off the delegate like So. And let's Cole this method from here, and we can run the app and look at the results. Let's do that. As expected, the output is equal to three end of the string representation. Off the funk delegate is this funk, which takes three integers. Okay, the wear method, as you've seen except an expression of funk so What is it? Let's wrap our funk by expression, like so the line off cold steel compiles without errors. However, the next line doesn't compile. We can't just call the expression as irregular. Delegate cold expression wrapped into the expression class represents a data structure which describes that code. In other words, if I commend out the coal toe ad and result and around the lab, you'll see our code written in text. It is the code body. If I run our rap in the debug mode, putting a break point like so you can see that expression provides some a P I related to managing and inspecting the wrapped gold. Now you can understand how linked to entities work. When we pass alarmed expression, it gets wrapped by the expression class and entity framework. Willens back to that cold in around time, translating it into sequel code that has to be executed by sequel server. So now you can understand why we face is not supported exception at run time. When we continue our matter chained by calling the contains method right here, Entity Framework will inspect it at runtime. It will conclude that it's not possible to translate it into a valid sequel code and throw the exception. And this is exactly that situation. Well, we can use the s innumerable method to break the like wearable chain and continue to build that chain using methods that can be executed locally by innumerable, which implements the contains method. For that, we need to call s innumerable toe up cast their like, wearable. So here I'll call the S Innumerable, like so now contains will be called locally using the implementation provided by the innumerable class itself. Let's run this code and check that exception will not be thrown and you can see that no exceptions have been thrown. So the only meaning off s innumerable method is to change the rails, so to speak. If you are on the rails off IAC wearable or any other queer arable interface and you want to execute your query locally at a certain point, you can call a saloon memorable when you need and continue to build the cold chain as usual . The aim off the ESC wearable method is similar. In my opinion, there are two main purposes off esque variable method. The 1st 1 is that you can use it to mock EC wearable data source. Using an in memory data source so that you can more easily test methods that will eventually be used on all non, innumerable based, like wearable. So when you pass, say an instance off, released as data in your test, you can call esque wearable. If you're Mark requires, acquire a bill to be passed, and the second you can write helper methods for manipulating collections that can apply toe either in memory sequences or external data sources. If you write your helping methods to use, like wearable entirely, you can just use esque. Wearable on all innumerable is to use them. This allows you to avoid writing to separate versions off every generalized helper methods for innumerable and I wearable. I'm going to demonstrate Second benefit here. Let's say I'm writing some public a buy for filtering, just players. Then I can expose them following method public ST ick like wearable off chest. Blair's order by rating taking a queria Beloff just blares like so and the return players Dodd ordered by player and its rating. Like so, this is a synthetic example, but it demonstrates that we can expose single method to serve both innumerable. Send Ike wearables. Let's cool order by rating in the separate Method Island's Done Shade Here and Chest Clear D B. We can call our order by rating method when we work with a remote set of data like this of our order. By ranging equals order by rating db dot chess players, which is a DB sad type. Yes, you should remember, and we can call it working with a local set of data of our chess players equals chess player dot Get them a list and of our buy rating equals order by rating passing chess players calling ass quite arable here like so in this case, the only thing we need to do is to call a square a ball. And the important fact here to notice is that working with a local collection, no additional performance cost will be incurred. Like Wearable is enough smart to understand that it works against a local collection, so everything will work its usual with a regular innumerable 59. 06 Conclusion: I could dedicate a separate course toe entity framework. Since it's a huge topic, however, we briefly looked at how to use linked to entities you learned that you can use linked to insert data to a data basis usual that you can use linked to retrieve data from a database s you did with the regular objects. But at the same time linked to entities hide some people, such as a lack off support off particular link operators and the necessity to understand the peculiarities of transforming link queries to sequel queries. Insured somebody inquiries can be transformed into plain sequel and execute on the server in a very inefficient way. So you always have to track down all the performance related issues that can arise here and there from time to time. Be careful with that. 60. 01 Outline: Hi. This is engineers block from engineers spark dot com, and in this section we're going to talk about functional programming in C shop. This section is going to be very practical. The majority of types built in BCL were implemented even before extension math. It's feature was introduced, so they were implemented without any thoughts about functional programming. However, everything is in our hands and we should care about laying out the ways for functional programming on our own. This is sometimes getting a little bit tedious, but it's worth of time spent on it. Okay, so what you're going to learn in this section? This section is all about extending the types to enable functional programming and making it widely applicable. So this section covers what is functional programming, the importance off functions in functional programming, the benefits of functional programming or, in other words, why we need to understand FB related concepts. What is immune ability and how important eighties in functional programming, what is purity and how it is related to side effects? And, by the way, what are side effects? Extending the I disposable interface, allowing disposable types to be used to build gold chains extending string builder is an example, demonstrating that we can extend anything we want implementing general extensions, saying, General, I don't mean generic. Though most of general extensions are actual generic, I mean that we need to implement some extensions which allow us to compose objects which have not been compose herbal yet. So let's kick off this section by defining functional programming. 61. 02 Defining Functional Programming: functional programming is a programming paradigm, a style of building the structure and elements of computer programs that treats compute ation as the evaluation off mathematical functions and avoids changing state and immutable data. It is a declarative programming paradigm, which means programming is done with expressions or declarations instead off statements in functional code that the output value off a function depends only on the arguments that are passed to the function. So calling a function F twice with the same value for an argument X produces the same result f off x each time. This is in contrast to procedures depending on the local or global state, which may produce different results at different times when called with the same arguments but a different program state eliminating side effects i e. Changes in states that do not depend on the function inputs can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development off functional programming. You can notice that we use the word function talking in terms off FB, and we tend to use the word method talking in terms off. Oh, this is because these two different paradigms street functions differently. Classic functions in F B are true mathematical functions, which return the same result as the answer to the same input, and a function expresses all the information about itself in its signature. It transforms the input to the output. Now we can see the difference between O P and F B. Yes, Michael Feathers. One sad oh max code understandable by encapsulating moving parts, F B makes goto understandable by minimizing moving parts. Oh is all about changing states of objects, whereas FB tries to avoid state changes at any means. If B implies that we build a system by sticking independent functions together, every function just depends on the input it receives and doesn't depend on any external state. F B is a paradigm which concentrates on computing results rather than on performing actions . You'll soon practice what it means very soon. As a result, programs written in a functional style are generally more predictable, easier to maintain and easier to test. Since you need to test independent functions, that means you don't need to use difficult marking techniques and other advanced oh approaches to achieve testable design. Oh, and the speed try to achieve the same goals with different approaches. Let's talk a little bit about functions in the next lecture. 62. 03 Functions Are Everywhere: the core concept off the object oriented programming is object. In Si shop, you even can declare a function outside of class. It is sin tactically impossible. I remember how I was astonished by this fact after programming in Old visual Basic, where we could declare global functions. Functional paradigm is based on the functions. Functions are the first glass citizens in cold basis. An interesting fact is that the best practices off implementing functions in Opie languages are lined with Howie right functions in functional languages. Here are those best practices. Keep functions small. Don't repeat yourself. There should be only one source off. Authoritative knowledge functions have to do only one thing. Avoid side effects. Functions should accept no more than three parameters. I like joke from the talk at NDC by scott slash In Every oh programmer knows about classic design patterns and principles and all the related stuff to tackle the regular standard problems which arise in the everyday basis, we'll know them single responsibility principle, open closed principal dependence, inversion principle and other solid principles. Strategy pattern, abstract factory pattern, decorated pattern visit or pattern terms of patterns. If we try to convert all these concepts into functional ones end up with the following. SRP transforms into functions so Sir Peas function soaks, appease functions in F B D eyepiece functions in F B strategy. Pattern is functions in F B abstract factories, functions, functions, functions, functions. Everything is functions in functional programming. This is, ah, humorous definition of the functional programming, which is very close by the way to the reality. Let's talk about why you need to learn more about functional programming. 63. 04 Why Functional Programming: so you may ask yourself again, why would they need to learn functional programming? You may also think that you'll never use a truly functional programming language. However, you don't need to learn truly f B language to harness the power of FBI ideas. Apart from that, you'll get a better developer learning new programming concepts and looking at the same code base from other perspectives. Considering different concepts. Believe me, after learning new fundamental programming concepts, you'll get a fresh look at what you did before. If I'd need to mark out the benefits off a functional programming style, I would list the following. Minimizing the code base functional style in the end leads to them more understandable and shorter. Code functional programming leads to constructing more compose herbal components, which have very high reusability. These benefits are very important, especially in enterprise development field. Since domains become more difficult to understand on every year basis, there is another benefit we haven't marked out yet. Local currency didn't expect yes. Indeed, a truly functional program is safe for concurrent access by default. The main problem of concurrent access is the possibility off damaging the shared state in the functional programming. There is nothing to damage scenes. There is no shared state. This is also one of the reasons which explain why functional programs are safer. They're more predictable. Okay, as was said before, functional paradigm in forces in mutability, off types functions with outside the facts and improved compose ability, off types and functions. Following all these principles together will lead you to improve design off your applications. 64. 05 Immutability: in mutability is one of the core concepts in functional programming. When are talking about mutability, we imply mutable or immutable objects. So what does it mean for an object to be immutable? It means that such an object doesn't mutate or change. In other words, it's internal state. Junior developers often get confused when hear about the mutability for the first time. Indeed, how is it possible to implement on an immutable type? However, any see shop developer can recall that this drink type is actually mutable. When you change the string instance, you get in you modified string. Instance. As a result, the initial instance Original one stays unchanged. This is a mutability, in essence. Okay, then let's look at a very simple code snippet. Here is the character class. Is this glass immutable? No, of course not. This class is mutable. The heat method mutates the internal state. It changes the value off the health property. We can't say that this is a very bad piece of code. However, we can make it better. We can make it immutable, automatically making it safe for concurrent access. At least, Actually, the benefits are more profound, and you'll see that later. So how to make this type immutable easily. Look at this. The heat method now returns a new instance on each call. It doesn't mutate the internal state anymore. This is exactly how the string type is implemented. Well, actually, not exactly, but similarly, let's look at another example, which demonstrates how mutability reduces readability. The first glass we see here is called a rectangle. This type is mutable, since the scale method mutates the internal state, the width and height properties. The next type we have here is called al Apps, and it takes a rectangle instance in It's Constructor. It takes their tangle to draw itself around that rectangle. We don't have a full blown implementation, since it doesn't matter from the learning perspectives. And now is the most interesting thing. Let's look at the client's code Logically. The color at first greats, in instance, of their Kangol type var wrecked equals new rectangle pressing, say, 10 and 20 as the arguments. And now the cooler should create an instance of the Ellipse type. So we were at a lips e l equals new al IPs passing that rectangle instance. And now let's scale Derek Tingle by the factor off to Uh huh, Interesting Looks nice looking only at this piece of clients code can you understand what will happen to the Ellipse after scaling their tangle. Seems like we mutate the internal state of their tangle Instance. But will the size off the al apps change correspondingly? Mm, This example demonstrates how mutability reduces their readability. Let's look at how we can improve design off these toy example. I'll co p and pace to these example into a new source file and change it to make their tangle immutable, weaken do the same trick we've done to the character type. Let's look at how the clients go change. Uh huh. Now we see that the scale method that returns in your instance off the rectangle type. That off course means that the Alps stays unchanged since the internal state off. Their tangle type obviously stays unchanged in the first place. That is a small but a very important improvement, which increases irritability and improves the predictability off the programs behavior. Let's look in the next lecture how to defeat the problem off temporal coupling by enforcing mutability 65. 06 Purity and Side Effects: so what? He's a side effect. Actually, you have to hear offside the facts since every one of us ever took a medication. So I'm sure you know what is a side effect of medication? Simply put, when we take a medication, we have an expectation regarding a direct result. Curing the disease, however, sometimes were observed something unexpected, a rash on the skin. That's a side effect. Usually we tend to think off side effects as something bad. Side effects in programming are similar, but they're not always bad. In terms of programming aside, the fact is an observable change made to the state of the system. Actually, many see shop developers special juniors immediately become puzzled, since they can't imagine a program which doesn't mutate any state. Okay, let's talk about it in more details. The definition we gave for aside, the fact is a little bit blurred. Let's have a look at some examples. So here's the first example. Does this function have a side effect? Well, probably not, because it doesn't hide anything. He takes two arguments and honestly returned the expected result. Okay, let's go to the next one. Does this function have a side effect, look more carefully. Can it produce some kind of side effect, which is observable from the systems point of view? Indeed, this function has side effects. What will happen if the second arguments value would be equal to zero? An exceptional the throne in such a case and an exception is always can be considered a side effect. Division guarantees by its signature that the result off in the integer type will be returned. However, its ally. Since there is a case which violates the declared signature, we refer to truly mathematical functions as to pure functions. However, you should understand that we treat functions. ESP. You're only to some extent don't get this concept literally. For example, in general, we can treat the previous function, which adds to values ESP. Your. Is that true? That it can fail ever off course? Not An exception can be thrown at the round time at any time in the managed environment. This is the sad truth. However, Any program depends on such factors as the global state off ram managed by the operating system, for example, so again don't get the concept of side effects. Literally, we make assumptions to some extent we can't avoid such assumptions. Otherwise, we can't treat any function in the world is truly pure. So when we talk about side, the facts and purity who abstract away all the factors which are outside of our control. But again, the function, which allows division by zero and which at the same time doesn't reflect it in its signature, is indeed not pure. How can we make that function? To be more honest, for example, we can declare it as a function which returns indelible ink and returns now in case of division by zero. After that, we need to reflect that no value is a special case in the XML comments or in the documentation. You could argue that instead, we could just reflect in comments that in case of division by zero, an exception is going to be thrown right here. Instead of writing new function. However, returning Malleable Inc is a more robust option from the statically typed language point of view. Though not an ideal one, we could change the signature by accepting some kind off from you type, which defines the allow the range more precisely excluding zeros from the range. Here's an example, we rolled out in Utah, called non zero integer, which encapsulate a number. It throws an exception in case off invalid argument passed into its constructor. Now everything is clear. Statically. That's a great benefit. However, The question is, Is it worth to roll out the whole new class? Well, the answer depends on the concrete case. It depends on the value brought to the system by introducing a new type. If that valley overweight, the increased complexity, then everything is fine. I started this rant to show what are side effects, what can be possibly done to remove them and that sometimes we may want to stay with side effects. I'll say a couple off words about when side effects are fine in a minute. Let's look at the next example. These function returns as some off two doubles. However, it logs the information down to the console, or it may have been writing into a file. For example, how do you think is this function pure well, most likely, these functions pure. Indeed, in 99% of cases, logs are not observable from the systems point of view. If logging have some influence on the systems behavior than such a function can be treated as impure. Let's look at the next example. The Cal method mutates the internal state off the object it assigns and you value to the local field. This function is impure, since such a mutation is a knob, those side effect. The next example is a classic example of a side effect. The first sign that the function has some kind of site. The facts is that it returns void. It means that the function does something and it doesn't return anything as the response. Let's get to the next example. These function is the definition of purity. It always returns the same value. It doesn't mutate anything, and it has no side effects. But okay, that was a simple function. Let's get to the next one. The next example is an interesting one. You see the function which returns the current second, Is this function pure or not? This function is not pure, since it returns different values each time being called, it doesn't mean this function is bad. Right now, we're only trying to understand what purity means in regard to formal definition. Okay, you've seen which functions can be treated as pure and which cannot. As I've said already, impurity doesn't mean something bad. In this lecture, we've seen what side effects are, in essence. 66. 07 Extending IDisposable: a significant number of types building the BCL are disposable. What means they inherit from the I disposable interface. Let's look at an example right away. You have a par sur named data sparser. The sparser processes a file in ah see SV format like this. A line contains two parts timestamp and the actual value the data Parsa exposes two methods . The 1st 1 is the ST Ick factor method to construct the object and the 2nd 1 allows to get values from the parcel. The factor method is preferred in such a case. Since he drowns a potential a long running operation. It's a bet practice to cram a long grinding operations into constructors. If you want to learn more about the best practice of building a P I since the shop, I encourage you to take my course AP and see shop The best practices of design and implementation. So and the constructor is private here. Okay, then what? The crate from string method actually does. It does what it says. It takes the continent s a string and parses it. At first, it splits the content by the new lion D limiter. After that, it goes through the air a splitting lines by the call on dealing Inter, adding the parse data into the corresponding dictionary. The cold is pretty procedural and we will tweak it. Of course, just in a couple of minutes. The value method just retrieves the value from a dictionary taking a time stamp as an argument. Unfortunately, this method can return now in case there is no corresponding data. Now values are what ruins functional style. So we will talk about removing now's in a separate section. For now, we will leave these unfortunate fact s cities. Let's look at the client's code. The manager glass contains the process method, which tries to use the data parcel. He defines a reference at first. Then it uses the stream reader wrapped in the using statement to read the file and construct an instance off the data Parsa type. Finally, it reads a value. As you see this goal this procedure less well only Imagine that this gold was the only way to do what we need before C sharp three. Let's see how to make this gold better. Well, I would extract out the construction off the data. Parse er, let's do that great. That was a tiny improvement not related to the functional programming. To convert the construction process into functional code, we need to enable building off gold chains on the I disposable types. Look at what we actually do here will create a type data parcel by using another type stream reader. We map one type to another. Actually, both parts can be represented by corresponding function signatures. Let's create a type which perhaps the using statement and allows to convert one type to another. We need an extension which can be applied to a type which inherits from the I disposable. So I'll create the state. A class tour allowed an extension method. Now I should implement an extension left, which has to work with two different types, one of which is I disposable. I'll name this method using and declare to generics. The first function which creates the disposable type instance, is going to be represented by the fund coffee, tea disposable and the function, which converts one type to another, is going to be represented by fun cough T disposable entity result. We also need to declare that the tea disposable has to inherit from the I disposable, so we need to ride the wear clothes. The remaining part should compose the functions. We accept its arguments. Everything is simple. The factory funk is wrapped by using statement and the resulting disposable type we passed to the funk, which converts one type to another. Let's look at how we can use this function now. - Look at how nature of this flow looks. Yes, we didn't reduce the number of Flynt's, but that was not the goal. The goal was to enable cold chains building. The syntax is not so appealing as in F sharp, but this is the price we have to pay for the fact that C Sharp is primarily an object oriented language rather than functional. Do you see the last line where we passed the value to the right line method? We can remove even these call, inserting it in our flow off consecutive calls. You'll see the corresponding technique in a couple of minutes. This technique is very powerful when we extend everything and use all the functional techniques In conjunction, you'll see other techniques like errors handling in the functional style. Further, in the end, you often right up to seven calls, and that becomes much more readable and safe. The benefits become apparent. Let's look at how we can improve the method which parses the content. Luke, how great it looks, how it is expressive. Okay, that was a great exercise. Let's practice a little bit further solving general problems which arise on the way off functional programming. 67. 08 General Extensions: in this lecture, we're going to fulfill the empty spaces on the way of building coal chains everywhere we want. The first problem I want to talk about is the problem you've seen in the lecture about extending the I disposable interface. Let's look at the client's code, which used the data Parsa, FBI charities. I'm sure you remember that. I said. We can stick the right line. Call toe the cold chain. Right now, the right line call looks like an orphaned procedural call. The general problem here is that we often need to pass an intermediate result into a call and then be able to continue our cold chain. Imagine that we need to log some value right in the middle of the cold chain. That's a quite common task. How to do that. I'm sure you know how to achieve what we want when you to implement an extension to make this possible, And this extension is going to be quite simple. Let's great in U. C s file for implementing general extensions, and it's going to be public ST ick in terms of programming. We need a function in this case, which passes down an instance off the current type two in action and then the returns, that instance back without any changes made to it. Let's implement it. There is an agreement about the name off this commonly used function we call it T. It takes an action, which accepts an argument of type T. It just calls the actions passing the argument and then returns the instance on which the cold was made without any changes. As we said before, everything is pretty simple here. Let's use this function to remove the orphans. Procedure will call. Let's get back. Oh, look at how nice it is, by the way, we even can convert it into a group call. This is even shorter. Sometimes we need to convert one type to another. By the way, it also happens in the middle of the cold chain. Often we start to build a cold chain on one type, then convert that type and continue to build a culture in on another type. Actually, we implemented an extension with a similar functionality. That was the extension off thy disposable type. But that was a special case with inherited I disposable interface, for example, we might want to convert the string instance into daytime instance. Let's right, the General extension for the purpose. This function is pretty simple. It works with two types, converting one to another so the signature will be the following would we need to do is just to call the map funk. Passing the source instance, I noticed that I used the expression bodied members in tax. We can do this without that Syntex, but that Syntex isn't the spirit of functional programming. Now we can use this extension to convert any type to another. The mapper should be provided at the client's side. Let's go back and use it. How nice. By the way, do you remember one off our first extension methods? We extended the daytime to convert the well into a device format. Nothing stops us from continuing the cold chain. The power of this technique is a manse. Imagine how this code would look like in a procedural style. This code is readable like a well written prose. Let's look at another case where we need a general purpose extension method. Sometimes we need to tweak the valley, which flows down the cold chain, depending on some condition. Mathematicians referred to conditions as to the so called Braddock, it's treat these terms equally. So. Imagine that, actually, the process method takes the time stamp as an argument. And it also takes an argument which says, whether we need to convert the daytime value into UTC before converting it into a device compliant format. By the way, I already added these arguments. I'll just use here the time stamp and I want to convert the daytime well into UTC when convert UTC flag is true. Sounds like we need a general extension, which takes to fund delegates. Let's implement it. - I called this extension when, Since you have a predicated here, depending on which we either passed the value into the processing function or not. If the Braddock it returns to, we call the processor. Otherwise we returned the original instance. Let's apply this extension to our example. Actually, this is a very bad practice of converting one day time a value to another. But this is a different story. If you want to learn the best practices related to working with dates and times, take my course dating time. Fundamentals in the Net on Sequel server Look at how nice the cold chain looks like I absolutely love it. Let's convert it into procedural code and compared to pieces off cold, hear how it would look like in case of procedural programming. But, well, I'm not going to lie. If you're just starting to practise functional programming, then the cold chain we built my puzzle us well as the procedural piece of code, However, there is a huge difference. Functional style cold chains will be much more readable to you as soon as you get enough practice in functional programming. I can't say the same regarding the procedural cold. It will always be obscure, and the main idea off a piece of code will stay obscure until you read and understand all the procedural piece of code. Procedural code introduces too much semantical noise into code. Functional style reduces this problem down to almost zero. Let's improve another piece of code with the power of general extensions, which are now it's our disposal. By the way, we can write the so many general extension sense we want in. Then you'll end up with a library off infrastructural code, which enables functional style of programming. You will extend that library for sure because there are many overloads required to apply functional style everywhere we want. Okay, let's get to the next lecture and practice What we learned. Repetition is the mother of learning. 68. 09 Extending StringBuilder: in this lecture, we're going to investigate one off cases from my own practice. Example. We're going toe work was modified and doesn't reflect the whole validation sequence I implemented. In the real world, however, the example is very close to the reality. Yes, I already said I developed a piece of software for point of service terminals which sold tickets for suburban trains. There was a case when a passenger could travel without a ticket because not all stations had ticket offices. In such a case, that passenger had to be able to approach a terminal at the arrival station and feel a special form. I don't want to dive deeper into why the Hackl. The things worked as they worked. Everything just worked this, I'm saying. So I needed to build a special report and then sanded by the network. Look at this code who have a pocho plain old CLR object here named Traveling for which store some data field by a user. After that, we have a view model which declared traveling for as property and terminal in four, which in the real world came from the upset ing's. When users done, he clicks on a button and the finish method fires up to create a report. Okay, we call the corresponding method off the report factor class. In the real world, that method wasn't static, but it doesn't matter for our discussion. Look at the method we're going to re factor. The method is written in a completely procedural or imperative style math. It creates an instance of string builder, then append align with two calls, then validates the carding for end in case of true appends one specific line. Otherwise it depends another line. After that it depends. Another one line with two calls. And then it goes through the least of terminal data, upending that data in a specific format. Looks like hell off course. I intentionally made this example look so bad we can make it better. By the means off object oriented programming, however functional style would be better. Anyway, let's start to reflector this piece of code right away. At first, we need to remove to line away offending a formatted line. Let's do this with the power of extensions. - I created a separate state, a glass for holding extensions off the string builder time. The extension I created takes two arguments. The 1st 1 is the string and the 2nd 1 for the string arguments. Everything is pretty simple and doesn't differ from what we did before. Let's apply this to simplify our code. I'll get back and replace all the A pen format and depend line goals to our new extension. - Great many alliance of cold have gone the call to the validate method and the corresponding logic resembles what we did with Wen Method. In this case, we need to roll out an overloaded version off that extension to be able to pass the handler off the failure or negative path. - Great . Let's get back and improve our code. Great. Finally, we need to remove the procedural loop. For that, we need to implement one more extension. - This extension is a little bit tricker. Sometimes you can get confused by the aggregate linke method. I'll get back and apply the newly created extension. - Finally , we can just call the to string method, returning the result who look at how nice this piece of code looks like. It is succeed and well readable. It is a pleasure to read such gold. One would say that we could avoid creating the upend formatted line extension, and he would be right before C sharp six. We could replace to calls by one call to upend line, injecting the string format inside. Look at it looks very ugly. Before C Sharp seeks, I would encourage you to rely on the extension method. After C Sharp six was introduced, I would agree that we could use the string interpolation feature instead of the extension method. Look at it looks beautiful. Noticed that string interpolation is also a feature related to functional programming. I decided to implement an extension method just to practice a little bit. Nothing more. I hope you enjoyed these sessions off, re factoring and learn many interesting and useful tricks. 69. 10 Primitive Obsession: the section shows how powerful method extensions can be. However literally any good feature can be abused with the feature of extension methods is not an exception from the rule, but before demonstrating you an example where extension methods actually to know. But practice, let me tell you a short story. There is a widespread opinion that decimal type is money, by the way, we even at the M Asaf ICS two decimal values. However, there is a tiny but extremely important difference between being money and being a tool for representing money. So decimal is not money decimal was invented for representing them. Let me explain in more depth the problem off representing money. In the rest of this lecture, I'm going to talk about money type as an obstruction instead of using decimal type for presenting money values. In the last project I have been participating in, we relied on the decimal and integer types for a long time. From the beginning, we knew that using primitive types for values off that kind is an anti pattern, but we stubbornly have been using them. This will loan anti pattern is called primitive obsession, representing I P address as a string or representing zip code, there's a string are quite good examples off these anti pattern. In short, zip code email i p address are in love complex concepts, which have to be represented by high level classes that encapsulate rules protecting in variants, which belonged to the implementation off a complex concept. If you represent emails using strings, then anyone can pass any string they want. It's an email mayna. Rules can be encapsulated inside the class such a zip code. For example. It can contain the mapping between codes and regions or something else representing ZIP codes by strings. You'll eventually see that all the logic related to ZIP codes is spread over the code base . So let's get back to the problem of representing money values in the US There are scents and dollars in the Russian Federation, rubles and Coptics, while ruble equals 100 coptics. So our System Inter operated with an external system which performed all its calculations in Coptics represented as integers. It required topics as the input and return Coptics as the output. If we wanted to pass in two rubles and 50 topics than we passed in the following variable and we haven't seen any problems up to a certain time. But those Coptics represented in in 32 started to spread throughout the whole system. In many cases, we've had to convert them into decimal type to correctly display the value on the screen. You definitely don't want to show users 250 car picks. You want to show two rubles, 50 car picks. In other cases when we handled users input off money values, we've had to convert them into complex in order to pass it'll into that external system. Eventually we found ourselves in writing the following function These function except toe arguments and have to answer other any mismatches between counters dispensing event arcs contained for integers that represent money values expressed in complex. As you can see, this go is very smelly. This is actually a ball of mud everywhere you have to elicit. What are you working with right now with topics or rubles? Then you have to convert them in tow, either Coptics or rubles, depending on the case, and only after that you can compare them from converting topics two rubles and vice versa. We wrote to extension methods called cop to Rubio and group to cop. Grating extension methods on primitive types is the first sign of the disease. So we ended up converting money values everywhere in our code base, even if you manage to avoid conversions in your domain logic, such conversions with last extension methods, will stand the boundaries off your application. You always have to be sure that you work with in a property type with an appropriate value stored in the type without riel protection. In the end, we decided to solve the problem by introducing money structure. It's a form of value object design pattern. Let's look at the money struck. This particular structure is made specifically for Russian currency. Imagine what will happen if you need to work with different currencies. How the hell willy Hello. Different currencies with different exchange rates, which, by the way, change frequently. Decimal is not enough. In such cases, you'd need something like this money structure or maybe a class just more sophisticated. The idea is that you need some kind of abstract entity to represent a complex concept. This is the only way to go. So these money structure implements I quit to compare, and I comparable to simplify comparisons on the client side. It defines the private constructor that takes decimal. The only way to get the money instance is to use either from Coptics or from rubles maths, passing either Coptics as long or rubles as decimal. In case your money is suited for a specific currency, that's a good idea. And here's why. Imagine that we made a construct republic but then declined Can ride the following code. What is that? $200 or 200 cents? This is also the reason why it is bad to allow implicit casts. It is bad in both cases, either. It's allowed to implicitly convert longer decimal into money. Really? Will you be sure that the expression money M equals 200 m does mean that it's $200? Maybe someone just put AM in order to compile it, but actually wanted to initialize it by $2. Consider the following to perform, add and subtract operations. I override the corresponding operators. The conclusion is that decimal is a good time. However, you should not examine the anti pattern called primitive obsession. Rely on an abstraction instead. Otherwise, you will spend hours to a factor the mass you brought to a project. It's also extremely easy to introduce box relying on primitive types. Remember, primitive types cannot reflect conceptions. Money is the concept. Decimal is close, but very often not enough. Don't try to cure any disease by the power of extension methods. Any tool should be applied where appropriate, don't apply to just because it doesn't feed from the first sight. 70. 11 Conclusion: congratulations. You reached the end of the section. That was an interesting section full of functional programming techniques. Let's recap what you learned. Functional programming Paradigm is the oldest one and stays one of the most applicable paradigms. The proper function definition is very important in if be functional. Programming treats computation as the evaluation off mathematical functions and avoids changing state and mutable data. F B enforces declarative programming style. What means programming is done with expressions or declarations instead of statements side . The facts are changes in state that do not depend on the function inputs. They make program harder to understand and predict its behavior. Programs written in a functional style are generally more predictable, easier to maintain and easier to test. Since you need to test independent functions, an object is immutable. If it doesn't mutate its internal state, you learn how to distinguish pure and impure functions. The guy disposable interface is easily extendable as well as any other interfaces. You learned a concrete example of extending the stream reader type. Any conversions. Passes of arguments, map ings and other mechanisms off managing the control flow are possible thanks to limitless extend ability, feature offset shop. Build any general purpose extensions You need to build gold chains. Don't hesitate and you'll be good to go further. You learned aerial world case of extending the string builder. I hope you enjoyed this section We covered almost told important aspects with face with on the everyday basis.