Click here to Skip to main content
15,885,278 members
Articles / Grouping
Article

Grouping records in a DataTable using LINQ

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
11 Oct 2013CPOL4 min read 50.9K   2  
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
-- There are no messages in this forum --