views:

184

answers:

3

Hi,

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

+1  A: 

From Shipment In OrderTable _

Group By Shipment.ShippingZip _

Into Total = Sum(Shipment.Cost), Average(Shipment.Cost)

JayJay
+1  A: 

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.

Pete OHanlon
+1  A: 

Basically a "group by" operation has two projections:

  • What do you want to group by? (The key)
  • What do you want the group to contain? (The value)

So for example, suppose we have a group of people. You could group their names by their age, e.g.

  • 18: Bob, Jeff, Dave
  • 21: Jennifer, Matt

etc.

If you're using the GroupBy method directly, you only have to specify the key selector, in which case the value selector defaults to "the value in the sequence" (e.g. in our example above, it would default to "group the Person objects by age").

If you're using query expression syntax, that will depend on which language you're using. You can effectively ignore the "into" part to start with though - that's just a query continuation; it's like saying, "I don't want any of the other variables I've used in the query any more, just the results of the grouping" (which you can then use in the subsequent bits of the query).

Jon Skeet