Grouping on DataSet Table AsEnumerable
By Peter Bromberg
You can use LINQ to perform GroupBy operations on a DataTable. Here is a short example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace LINQGroupBy
{
class Program
{
static void Main(string[] args)
{
string cn = "server=(local);database=northwind;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(cn);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM EMPLOYEES", conn);
DataSet ds = new DataSet();
da.Fill(ds);
var grps = from n in ds.Tables[0].AsEnumerable() group n by n["ReportsTo"] into grp select grp;
foreach (var g in grps)
Console.WriteLine( g.FirstOrDefault()["LastName"]);
}
}
}
Grouping on DataSet Table AsEnumerable (589 Views)