Thursday, 16 August 2012

Using Group By keyword in LINQ to Sql



Using Group By keyword in LINQ to Sql   


Frist  we  create a table TotalItem  in DataBase ForLinq
use ForLinq
Create table TotalItem(Id int,Item int)

insert record in table TotalItem  in DataBase ForLinq

insert  into TotalItem values(3,65)

select record table TotalItem  in DataBase ForLinq

select * from TotalItem

using  group by in table TotalItem  in DataBase ForLinq

select id ,Sum(item) as TotalItem from TotalItem group by id



How  to  use  above Concept  in LINQ (Linq  to Sql)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GroupBy : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       

    }
   //Create object for dbml class

    DataClassesDataContext dd = new DataClassesDataContext();

    protected void BGroup_Click(object sender, EventArgs e)
    {
        var v = from m in dd.TotalItems
                group m by m.Id  into g
                select new
                {
                    id = g.Key,TotalItem = (from w in g select w.Item).Sum()

                };
//Result  display  in  a  GridView  which name  is  GridView1

        GridView1.DataSource = v;
        GridView1.DataBind();


   //Result  display  in  a  Label  tabular  from  which name  is  Label2

        Label2.Text = "<table style='background-color:red;border:5px solid #CCC;'> <tr><td style='color:green;'>Id</td> <td style='color:green;'>Total</td></tr>";
        foreach (var v1 in v)
        {
            Label2.Text += "<tr><td> " + v1.id.ToString() + "</td><td>" + v1.TotalItem.ToString() + "</td></tr>";
        }
        Label2.Text += "</table>";

}
}






0 comments:

Post a Comment