LINQ in C# - DevChatter Basics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello my name is Brendan Enric and I'd like to welcome you to dev chatter basics in this episode we're discussing link in c-sharp we'll be going through some of the ways that we can use link in c-sharp to change the way we write our code whether you've been using the language for years or you're just starting with it a good foundation of the basics can help improve your coding skills get comfortable as we learn about link when c-sharp developers talk about link it would make sense if we all meant language integrated query as that's where the name came from it's usually not what we're talking about though the code we're seeing here is using what's called the query syntax of link it's the actual integrated querying in the language you might find this somewhere so I'll talk about it a bit at the end of the video for now though we're going to focus on the extension method syntax of link in c-sharp and if you haven't seen how extension methods work or how to build them go ahead and check out our previous depth chatter basics video on extension methods this is the method syntax doing the same thing as the previous query we were viewing we call it the method syntax because it has the same functionality as the link query syntax but instead uses these chained methods that are included in the system dot link namespace let's have a look at what's going on here first we created an array of integers and stored them in a variable number with the type int array next we declare a more complex type an ienumerable of integers and into it we assign the rest of our link methods we take the numbers array the where we'll filter down the numbers to only those less than 10 and then we order them by the number itself and we put it in ascending order if we wanted the result to still be an array we could add another method to the end of the chain and we'd end up doing this code instead returning an array of integers the plan for this episode is to do some hands-on explanation as we code so let's jump in and I'll explain how each of these works here we are in Visual Studio code and I've started up a basic console application and we haven't really done anything with it yet all it is is a standard hello world so let's go ahead and run it just to confirm that it does run so we'll do a dotnet run and this is going to print back HelloWorld so we want to take a look at link in order to do this the best example that we can do for starting out is to get ourselves a collection so let's make a collection we'll start off by making it an array we'll call this numbers and our numbers array will be a new array and in that array we are going to put in some numbers so this is our starting array and we can do some nice little things with it if we take these numbers and we only want to get the odd numbers for example we could write numbers dot where now when I do this something happens if we look up here using system but if I go control dot I can add a using system dot link and I mentioned earlier that if you are interested in learning more about extension methods you should take a look at our dev chatter basics video on extension methods this is an extension method that is part of the system dot link namespace so when we use where you can see that where takes an argument that is going to be a function that receives an integer and returns back a boolean and this functions called predicate but that's really saying essentially your predicate in this case just think of that as saying filter so where has a filter and this is the function that helps us filter it helps us determine for any given integer should we keep it or should we remove it and that's what the boolean means if we should keep it we return true if we should remove it from the set we say false now I want to clarify this does not remove them from the int array that we started with so the numbers array will always have that scent but we're going to remove some of them from our result so let's go ahead and say int array filtered numbers equals this and if I say dot to array on the end then we'll end up with an array so let's write that filter predicate so we'll say if X percent two equals zero this will return back any number that when divided by two has no remainder so that means get any of the even numbers now if you're not familiar with lambda expressions we will be doing a def chatter basics video on lambda expressions as well to explain how these work but the quick answer is this is the parameter of a function and this is going to be our integer we specified when we describe the function this says hey the right-hand side is going to be the actual expression that is the function and this is the return value so we're returning X percent to equals zero okay let's go ahead and print these out and when we run this we can go ahead and dotnet run and we'll get back to four six eight if we were to change this and we said instead does not equal zero so that means where the division would be having a remainder that means we're gonna get the odd numbers and if we run this we get 1 3 5 7 and 9 so this filter is really just determining which numbers should be kept in this new collection and that's how we're works let's go ahead and take a look at how ordering works so this set of numbers I wrote in here is in order but if we were instead to say and we'll even throw in some repeats so there's a set of numbers and again if we run this we get back 5 7 3 & 1 and if we switch this to show the even numbers we get back this set notice in both of these cases the collections were not in order with link we can go ahead and do an order by we can just say order by the value itself when you're ordering by a more complex type you need to specify what property of it you want to order by so for example if you had a collection of people you might order by their last name or if you have a collection of products someone might want to order by price or by their review rating when we run this code we should now see the numbers in ascending order and the same thing goes if we look at the odd numbers you so there's the odd numbers in order okay let's take a look at order by descending you can probably guess that order by descending does the reverse of what we just did I'm not going to run through all of them but you'll notice that it went from one three five seven two seven five three one okay so that is order by this was where and then we did a two array now it's fairly common for people to write these in this way because you can kind of see the steps we had numbers we said okay numbers where it was an odd number and order by is that and then we have our two array which tells it to store it in an array now we could leave this as an ienumerable it doesn't have to store it as an array because the result if we look at this is an I ordered enumerable the result of this one is an ienumerable so we do have those those types but a lot of people like working with arrays so we we did that and it's a small set so it works fine next we can do a couple of other things we could skip the first one every time and this will actually tell it to leave off the first number so if we run this instead of seven five three one we should just get five three one and there you go so skip lets us do that and now in addition we could just say to take two maybe we only want to get the second and third number but nothing more and then we just get five and three so skip and take allow us to decide how many we want and for any one that's that's wondering right now what happens if I do go beyond the array you'll notice that it just continues taking until it reaches the limit and returns back whatever it found so if you want to take them all leave off take but if you want to limit it just say hey I only want to take ten now keep in mind that your result might not include 10 but you didn't want any more than that let's remove the skip and the take you can also use a take while and this does a predicate so we could do the same thing we did before and say take while X is greater than 3 so this would return back only the only the items that are odd numbers that are greater than three and since we ordered that means as soon as we hit a three will bail out if we were not ordered keep in mind that this would cause us to bail out as soon as we found that one so this returned back seven and five link has a whole bunch of helpful little methods to let us do all of these kinds of things let's take a look at the next most important thing that's going to be the select extension method in order to show the select extension method it's best to use a complex object so let's start by creating a new type so we've created a new type called person and on that person we have name and age so let's make our collection be names and ages instead of being integers once created we need to make sure that we give each one of these the properties that they should start with so now we've got some fake data created that has some unique people but we've also got repeat names last names we've got some ages with some similarity so a reasonable amount of data to work with in inside of a collection let's get rid of our where let's rename this from numbers to people we'll get rid of this and order by descending like this is not gonna work because we can't just sort by person so this says sort by the person let's instead try sorting them a little differently let's sort them by age for example so in order to do that we specify what property on our person object inside of these linked expressions we receive one instance of each object inside of our lambda expression here and choose what property on it we want to access so we're saying order by the age and this is going to be descending so it means this will be the first record and then this one and this one and so on so let's write these out as well I mentioned that the important feature that we needed to talk about the new extension that we needed to discuss is called select so let's go ahead and use it here so we'll say select and again we're gonna do another lambda expression and we're gonna say name so essentially what this says is take all the people in our person array specifically our one that we have ordered and select their name so in this case what that means is take that value and make that be the only one in a new collection so this will return back and enumerable a we'll consider that to be a collection in this circumstance that is just the names so let's go ahead and run this and see what happens and there we go it printed out the names of the people in order now that's kind of useful but it obviously didn't print it out really the way we wanted it because we probably want to show some information because we can see that's the order but we can't see their ages so let's go ahead and put that in there as well so I said that this was selecting the name but inside of a select we can actually do whatever we want so let's illustrate that by making this a little bit clearer so instead of having this here let's go ahead and extract out a local variable and this illustrates an amazing point right here so what I've extracted this you can see that the return value of the Select is actually an Ino Birbal of string let's get rid of the namespace just to make it a little bit clearer so we end up with an ienumerable string will tell the s code to add that using statement at the top so this was the prefix namespace that was there before and then we have ienumerable of string no we had talked about that and i said that we could just to array this now this is not an efficient way of doing this because I have two listed twice so we don't have to do this part here we can instead put this same select that we did here into this one and now that collection instead of being an array of people it will be an array of string because we're selecting the name property off of it and the name property is a string so we have essentially changed what type this collection is by using the Select let's go ahead and take this value and put it in here again and now when we run this we should get the exact same result but now when I show how to do this it should be a little clearer what's going on I'm going to write this as string interpolation if you haven't seen this in c-sharp this essentially is a string and we're going to put variables inside the string so it's going to create it so this is a string which we're going to put the full name in and then after that we're going to add in another property from that object so we're gonna add in the name and the age and now you can probably guess what this is going to do but this is actually now going to give us a collection that includes both the name and the age of each one of these people and that works really nicely the link statement that we've got here has a couple of parts to it it says take all the people order them by their age and then turn it into a string now remember that these had to happen in this order because if I go this way we take the people we turn it into a string and there no longer is an age property because the return value of the select is an ienumerable of string so that means we can no longer order by age because there is no age property because string doesn't have one see how the X here is a string now so the order does matter on these and it will determine how those pieces run so we've said take the people order and extract it out into a structure so essentially take those parts and put them the way that we want it now these can be used for other means as well it doesn't just have to convert it into a string you can actually use selects to create more complex objects so for example if I had a an array of strings that were all like written out date times I could inside of a select statement parse all of those into a date time object and I would end up with a collection of date times so essentially link is just giving us ways of manipulating data and that's what makes it so powerful inside of c-sharp is we have a lot of ways of manipulating data that don't require that we create lots of loops and and lots of other structures so it's really nice for that let's go ahead and run this just to make sure we didn't break anything because we were moving things around and works like a charm so we have ordered by age I don't want to do that anymore we're gonna show a new thing so instead of ordering by age I want to do a group by now this is a more complex part of link so we're diving it a little bit further when we talk about group by group bys responsibility is to take a collection of data and group it based on some similar attribute that the items in the collection will have that in this case is going to be the age I want to get how many what decade they are in so people in their teens 20s 30s and we're gonna group by that so we're gonna say group by and every time we use one of these linked statements it's always gonna take a lambda expression but pretty much all art and it's gonna give us an individual item in the collection so this is gonna be a person object and from that we're gonna say X dot age and we're gonna say divided by 10 now if you remember your integer math you'll know that when I divide by 10 we're going to lose the remainder so 18 divided by 10 is gonna be 128 divided by 10 is gonna be 2 and 38 divided by 10 will be 3 so we just lose off the the remainder and that's going to group us by decade when we do that we get back a different object notice that in the select I'm getting little squiggly underlines here let's go ahead and select a little bit differently people in there X dot key now in this case this value that we created here this is the key because that's what we have grouped by so we have grouped by this value so this is going to be their key and we're gonna say times 10 so it'll say their you know tens their 20s their 30s we could obviously translate this into words like teens 20s 30s but that's beyond the scope of this and we're going to say a number let's put it inside of these parentheses why don't we say X dot count and this will give us the count of the people that are in that set so people in their tens there are two people in their 20s there's one and people in their 30s there are two so we're able to take this data group it based on a calculated value and get back the result so that's pretty darn powerful that's some amazing stuff that link is getting us here let's take this one step further so we said people in their tens and we said the number we printed out the count but I don't want to do that I want to actually show them so let's do this let's instead of saying count let's say select so we're gonna actually now select their name into this now this isn't gonna be perfect because this is still not an actual value here so I want to get a little bit better with this so let's go ahead and string join them as well so let's do string don't join just like we did below it's the exact same thing and just to make this a little clearer I'm gonna get myself a new line so we're gonna say string join and we're gonna pass in that select so this code should go ahead and put those in there so now it says people in their tens there's Brendon and Rick and Brendan Smith people in their 20s Michael and then people in their 30s and it lists out very nicely in that structure now obviously we're not writing console applications that print out names and strings but hopefully you can see the power of manipulation that we can get through selecting objects and working with group bys so when you think of this just remember after you've done a group by you're now working with a grouping so it is the key and remember that X itself also contains all the items so notice I was able to select that grouping to get individual items so you have the items and you also have the key that you use to group them that's all a grouping is it does seem complicated and it is a difficult concept to understand but hopefully this helps you to grasp that concept so group bys really really powerful there are a number of other linked concepts that we could dig into there are select many's now let's just take a look at a few of them so there are the accepts there's distinct there are we already did the group by for example you can check the last item you can check the first item you can check a single you can do all kinds of things with with link to get this data and and manipulate it but I don't want to show you all of those because that will take too long and is a little bit complicated so let's show a couple of other things and we'll take a look at that first off let's just cover really quickly so we'll do linked people dot last so that should get us our last item this should get us our first item because you should know what those are and then I'm gonna have this program so we're gonna run it but then I'm gonna make it throw an exception in a minute so first off we're gonna run this so it printed out the whole thing here and then it printed out the first item and then the last item so again remember our linked people is an array of strings so that's why we're printing out that whole string now if I want to make it throw an exception I can do single and what I do single is actually going to throw an exception because there's not just one now I'm also going to show you one more gotcha so if we do first or default that will work fine so the or defaults when you see that what that stands for is grab the first one or if there are none go ahead and give me the default value for that item so in this case a person object the default value is null in this program so we're gonna receive back a null object and that's fine now obviously we had items in the collection so it didn't return back no but the same would go for last or default again if there were zero items in the collection it would return back no the exception the the one that usually gets people though is single or default and when you use this one it still throws the exception and the reason why is because the single or default throws an exception if there's ever more than one whereas the other two work fine if there's more than one so if you know that there's only supposed to ever be one you want to put in single instead of first because single will throw an exception and alert you the developer to the fact that there is something wrong with the code and that's one of the useful features and potential gotchas in link will save looking at further parts of link for a future episode of dev chatter basics thanks for learning about link with us join our live streams on twitch at twitch.tv slash dev chatter if you enjoyed this video be sure to click the like button and subscribe to dev chatter to catch all of our future episodes happy coding [Music] you
Info
Channel: DevChatter
Views: 936
Rating: undefined out of 5
Keywords: Programming, Software Development, C#, .NET, .NET Core, DotNet, DotNetCore, Object Oriented Programming, DevChatter, CSharp, LINQ
Id: QunK6pb2sv4
Channel Id: undefined
Length: 27min 51sec (1671 seconds)
Published: Mon Apr 13 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.