How do I group a property in a collection of objects using LINQ?
I have a set of objects like Dim XXX As IEnumerable(Of MyObject)
that has been populated. MyObject has a property that I want to group, like MyObject.MyCode.
Looking through the LINQ examples, it is not clear what the syntax does Group XX By INTO
and I cannot figure it out.
So what I need is the ability to group the MyCode value and see how many of each value I have in XXX.
I know I haven't explained this well, but hopefully the LINQ person gets it.
thank
Ryan
source to share
The following C # code shows how to do this (sorry, but I don't really like VB.NET person):
var myGroups = from p in myObject
group p by p.MyCode into g
select new { Category1 = g.Key, Category = g };
The keyword takes the group result by default and puts it in a new element that you can refer to in your section.
source to share
Basically, the operation "by group" has two projections:
- What do you want to group? (Key)
- What do you want the group to contain? (Value)
So, for example, suppose we have a group of people. You can group your names by age, for example.
- 18: Bob, Jeff, Dave
- 21: Jennifer, Mat.
and etc.
If you are using the GroupBy method , you only need to specify a key selector, in which case the default selector is "value in sequence" (for example, in our example above, the default will be "group objects Person
by age").
If you use query expression syntax, it will depend on which language you are using. You can effectively ignore the "c" part to start with it — it's just a continuation of the query; it says, "I don't want any other variables that I used in the query anymore, just the grouping results" (which can then be used in subsequent bits of the query).
source to share