How to: Aggregate Data

An aggregation operation computes a single value from a collection of values. An example of an aggregation operation is the calculating of the average daily temperature from a month's worth of daily temperature values. This topic shows how to group orders' details by CustomerID and get the average unit price for each CustomerID.

To run the code in this example, you need to create a new Telerik Data Access Domain Model based on the Northwind database.

The following code is the LINQ example.

using ( EntitiesModel dbContext = new EntitiesModel() )
{
   var query = from orderDetail in dbContext.OrderDetails
               group orderDetail by orderDetail.Order.CustomerID into o
               select new
               {
                   CustomerID = o.Key,
                   AverageUnitPrice = o.Average( od => od.UnitPrice )
               };
   foreach ( var item in query )
   {
       Console.WriteLine( "CustomerID = {0} \t Average UnitPrice = {1}",
           item.CustomerID, item.AverageUnitPrice );
   }
}
Using dbContext As New EntitiesModel()
 Dim query = From orderDetail In dbContext.OrderDetails
    Group orderDetail By orderDetail.Order.CustomerID Into o = _
        Group Select New With _
        { _
            Key .CustomerID = CustomerID, _
            Key .AverageUnitPrice = o.Average(Function(od) od.UnitPrice)_
        }
 For Each item In query
  Console.WriteLine("CustomerID = {0} " & vbTab & " Average UnitPrice = {1}", _
      item.CustomerID, item.AverageUnitPrice)
 Next item
End Using

See Also