Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Grouping records in a DataTable using LINQ

0.00/5 (No votes)
18 Sep 2011 1  
While answering forums I come across a post “Grouping the data in the data table” which lead me to write this short code snippet for that post. 

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

While answering forums I come across a post “Grouping the data in the data table” which lead me to write this short code snippet for that post. 

Using LINQ-DataSet extension methods I got the data grouping the data table and displaying them on the screen. Refer the following MSDN link which gives you overview of the LINQ to DataSet concepts and new extension added to handle the data table uisng Language Integrated Query(LINQ).

http://msdn.microsoft.com/en-us/library/bb399399(v=VS.90).aspx

With new extension provided you can write the the queries as you write in SQL.

Refer the following link for Samples from MSDN using C#, VB.Net.

http://code.msdn.microsoft.com/LINQ-Sample-Queries-13a42a54

Below is the sample which gives you grouping using the DataTable and display them on the screen

Here is the Markup

<asp:Repeater ID="GridView1" runat="server" OnItemCreated="GridView1_OnRowCreated">

            <ItemTemplate>

                <span>

                    <b><%# Eval("Column1") %></b>

                </span>

                <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" BorderStyle="None">

                    <Columns>

                        <asp:BoundField DataField="Column2" HeaderText="Column2" />

                        <asp:BoundField DataField="Column3" HeaderText="Column3" />

                    </Columns>

                </asp:GridView>

                <hr />

            </ItemTemplate>

        </asp:Repeater>

Here is the Code:

v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} Normal 0 false false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin;}

While answering forums I come across a post “Grouping the data in the data table” which lead me to write this short code snippet for that post. 

Using LINQ-DataSet extension methods I got the data grouping the data table and displaying them on the screen. Refer the following MSDN link which gives you overview of the LINQ to DataSet concepts and new extension added to handle the data table uisng Language Integrated Query(LINQ).

http://msdn.microsoft.com/en-us/library/bb399399(v=VS.90).aspx

With new extension provided you can write the the queries as you write in SQL.

Refer the following link for Samples from MSDN using C#, VB.Net.

http://code.msdn.microsoft.com/LINQ-Sample-Queries-13a42a54

Below is the sample which gives you grouping using the DataTable and display them on the screen(Ref: Below figure).

 

public partial class Grouping : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                GroupByDemo();

            }

        }

 

        private void GroupByDemo()

        {

            DataTable table = new DataTable();

 

            table.Columns.Add("Column1", typeof(string));

            table.Columns.Add("Column2", typeof(string));

            table.Columns.Add("Column3", typeof(string));

 

            DataRow row = table.NewRow();

            row["Column1"] = "Admin";

            row["Column2"] = "xyz";

            row["Column3"] = "cleaning";

 

            table.Rows.Add(row);

 

            row = table.NewRow();

            row["Column1"] = "Admin";

            row["Column2"] = "hjkj";

            row["Column3"] = "washing";

 

            table.Rows.Add(row);

 

            row = table.NewRow();

            row["Column1"] = "Rishi";

            row["Column2"] = "iuyiu";

            row["Column3"] = "locking";

 

            table.Rows.Add(row);

 

            row = table.NewRow();

            row["Column1"] = "Rishi";

            row["Column2"] = "uyur";

            row["Column3"] = "contracting";

 

            table.Rows.Add(row);

 

            row = table.NewRow();

            row["Column1"] = "Rishi";

            row["Column2"] = "qewq";

            row["Column3"] = "launching";

 

            table.Rows.Add(row);

 

            var groups = table.AsEnumerable();

 

            var groupList = from g in groups

                            group g by g.Field<string>("Column1") into Group1

                            select new { Column1 = Group1.Key, Properties = Group1 };

 

            List<DataClass> newList = new List<DataClass>();

 

            foreach (var item in groupList)

            {

                newList.Add(new DataClass() { Column1 = item.Column1, Properties = item.Properties.ToList<DataRow>() });

            }

 

            GridView1.DataSource = newList;

            GridView1.DataBind();

        }

 

        protected void GridView1_OnRowCreated(object sender, RepeaterItemEventArgs e)

        {

            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)

            {

                GridView GridView2 = e.Item.FindControl("GridView2") as GridView;

                if (GridView2 != null)

                {

                    DataClass dataClass = e.Item.DataItem as DataClass;

                    if (dataClass != null)

                    {

                        GridView2.DataSource = from l in dataClass.Properties

                                               select new { Column2 = l.Field<string>("Column2"), Column3 = l.Field<string>("Column3") };

                        GridView2.DataBind();

                    }

                }

            }

        }

    }

 

    public class DataClass

    {

        public string Column1 { get; set; }

        public List<DataRow> Properties { get; set; }

    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here