This documentation is archived and is not being maintained.

How to: Aggregate Data

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

The same example is shown using LINQ to Entities and Entity SQL:

The example in this topic is based on the Adventure Works Sales Model. To run the code in this topic, you must have already added the Adventure Works Sales Model to your project and configured your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework) or How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework).


The following is the LINQ to Entities example.

using (AdventureWorksEntities context = new AdventureWorksEntities())
    ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;

    var query =
        from order in orders
        group order by order.Contact.ContactID into g
        select new
            Category = g.Key,
            averageTotalDue = g.Average(order => order.TotalDue)

    foreach (var order in query)
        Console.WriteLine("ContactID = {0} \t Average TotalDue = {1}",
            order.Category, order.averageTotalDue);

The following is the Entity SQL example.

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
    string esqlQuery = @"SELECT contactID, AVG(order.TotalDue) 
                            FROM AdventureWorksEntities.SalesOrderHeaders 
                            AS order GROUP BY order.Contact.ContactID as contactID";

    foreach (DbDataRecord rec in
        new ObjectQuery<DbDataRecord>(esqlQuery, context))
        Console.WriteLine("ContactID = {0}  Average TotalDue = {1} ",
            rec[0], rec[1]);

See Also