Showing posts with label Top N Record. Show all posts
Showing posts with label Top N Record. Show all posts

Sunday 16 September 2018

Top N Record using LINQ in C#

In this post, I will explain how to get Top N Record using LINQ in C#. 

In below example, I want a record of top 3 employees based on their salary. To get the top 3 records using LINQ I have used Take() extension method of LINQ

LINQ Query in C# : 

 int N = 3;

var employees =
    db.Employees
    .Select(emp => emp)
    .OrderBy(emp => emp.Salary)
    .Take(N);

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


Employee Table Script:

CREATE TABLE [dbo].[Employee](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [varchar](100) NULL,
[DepartmentId] [int] NULL,
[Salary] [decimal](18, 2) NULL,
[Age] [int] NULL,
[ZoneId] [int] NULL,

)


LINQ
Employee Table

LINQ
Top N Employee Record