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

post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts