I’m using VB.NET on Framework 2.0. I’m looking to quickly group a Generic List<> by two properties. For the sake of this example lets say I have a List of an Order type with properties of CustomerId, ProductId, and ProductCount. How would I get the average of ProductCounts grouped by CustomerId and ProductId in VB.NET ?
Unfortunatly I cannot do this at DB level (which would have been easy). Also I cannot use LINQ or Lambada as Im on Framewwork 2.0. So I need to do this at application level in VB.net. The list is returned to me sorted by CustomerId and ProductId so I guess with a few loop sI should be able to create a average value for but there must be a cleaner way to do this?
This type of problem is a great example of why LINQ was introduced in C# and VB.NET. In .NET 3.5 and above, LINQ provides the “cleaner way” that you are looking for to solve this problem.
Unfortunately, because you are using .NET 2.0, you’ll have solve the problem in a more or less “manual” fashion. However, you can still write clean code by encapulating the functionality you are looking for into well-defined classes and methods. This is one (but not the only) of the benefits of LINQ, i.e. that it encapsulates the functionality you expect in a clean, declarative manner.
Here’s some sample code to get you started:
The nice thing about inserting your data into well-encapsulated classes is that the consuming code is very succinct and easy to understand. Also, since you already have your data aggregated into an
AggregateItemclass, you could easily extend that class with more methods such asGetSum()orGetMax().Obviously, you could continue on this path of abstraction to get better re-use out of your code, but I would think that this gives you a good start.