Blog

Group By In Linq To Sql

Posted by Sandeep Singh Shekhawat Blogs | LINQ Dec 03, 2012
In this blog I am going to explain how can use group by clause. I have an EMPLOYEE table and want to sum of salaries as per employee name.

In this blog I am going to explain how can use group by clause. I have an EMPLOYEE table and want to sum of salaries as per employee name.

1.     1.  Create Data Context Class: 

First of all create a data context class that has an EMPLOYEE table.

empDataContext.PNG

1.      2. Create UI Design : 

I use grid view to show employee data.

       <asp:GridView ID="grdEmployee" runat="server"></asp:GridView>

3.   Original Data : 

Here I show whole data these contain by EMPLOYEE table. 

   SELECT * FROM EMPLOYEE

    originalempdata.PNG

4.       Group By in Sql Server:

Here I write a query in sql server's query editor to get employee name and salary.

    SELECT Name, SUM(SALARY) AS SALARY FROM EMPLOYEE GROUP BY Name

    sqlgroupby.PNG

1.       5.   Group By in Linq To Sql

      Here I create data context class object. This object contains employee data.

private void GetEmployee()

    {

          EmployeeOperationDataContext employee = new EmployeeOperationDataContext(); 

          var salarySum = from emp in employee.EMPLOYEEs

                             group emp by emp.Name into empg

                           select new { NAME = empg.Key, SALARY = empg.Sum(x => x.SALARY)}; 

        grdEmployee.DataSource = salarySum;

        grdEmployee.DataBind();

    } 

   Output:

groupbylinq.PNG

COMMENT USING
PREMIUM SPONSORS
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.