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,
)
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,
)
Employee Table |
Top N Employee Record |