R – How to group by a property in an object collection using LINQ

groupinglinqnet

I have a collection of objects as Dim XXX As IEnumerable(Of MyObject) which has been populated. There is a property in MyObject that I want to group by, for example MyObject.MyCode.

Looking through the LINQ examples it is not clear what the Group XX By INTO syntax is doing and I can't understand it.

So what I'm after is the ability to group by the value of MyCode and see how many of each value I have in XXX.

I know I've not explained it well, but hopefully a LINQ person will get it.

Thanks

Ryan

Best Answer

The following C# code shows how to do this (sorry, but I'm not much of a VB.NET person):

var myGroups = from p in myObject
               group p by p.MyCode into g
               select new { Category1 = g.Key, Category = g };

The into keyword basically takes the result of the group by and puts it into a new item that you can refer to in your select portion.