Thursday, November 12, 2009

A Complete C# Example LINQ DataTable Query - Group Aggregation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            DataTable table = new DataTable();
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Value", typeof(decimal));
            table.Rows.Add(123, 4.0M);
            table.Rows.Add(123, 5.0M);
            table.Rows.Add(234, 1.0M);
            table.Rows.Add(345, 2.0M);
            table.Rows.Add(345, 3.0M);

           
            var query = from row in table.AsEnumerable()
                        group row by new
                        {
                            Id = row.Field<Int32>("Id")
                           
                        } into grp
                      
                        select new
                        {
                            Key = grp.Key,
                           
                          
                            SumValue = grp.Sum(r => r.Field<decimal>("Value")),
                           
                        };

            foreach (var grp in query)
            {
                Console.WriteLine("{0}\t{1}", grp.Key, grp.SumValue);

            }
            Console.ReadLine();
        }

    }
}

2 comments:

Followers

Search This Blog