From the course: .NET Essentials: Working with LINQ

The GroupBy method

- [Lecturer] You can take a sequence and split it into groups. So when you split it into groups with the GroupBy Extension Method, it turns it into a sequence of groups. And each one of those groups has two defining characteristics is their key that defines the group, and the value which are the items that belong in that group. If you've worked with dictionaries, this sounds familiar, you got a key value, the grouping in link is very similar to working with dictionaries, it's just that the value is also a sequence itself. So you're going to end up with multiple sequence, one sequence that contains the groups and then each group will have its own sequence, which are the items that belong in that group, and they are placed in what's called The Value. This makes more sense when you see it in action. In this example, we'll use the GroupBy Extension Method, I start on line nine by getting my web colors and then on line 10, I call that GroupBy Extension Method and then I give it an expression. The expression is what splits it into groups. So in this example I'm telling you to split based on the color family. All right, let's see this in action around the query. So I get a sequence of 11 items. There's 11 color families. And you can see that my sequence is of type IEnumerable of IGrouping of color family comma web color. So color family represents the key. And web color represents the value or the sequence. So I'm going to have a sub sequence of web colors. That's what you're seeing here. So there's the key red, and here are all the red items. Down here I have the key of yellow and there are my yellow items. There are 10 of those. And then my key of orange, I've got six orange items. That's the basics. Since we're getting back a sequence of groups, we can apply any of the other link techniques we've learned earlier. For instance I'm going to just pull out one of the groups. That's what I'm doing here on line 14. I'm using ElementAt to retrieve one of the groups. Let's see what we get when I run this example. Now I'm getting just the orange group, and I have just the six sub items in there. So that's the basics. There is also a query expression version of this. Let's take a look at that in the next video.

Contents