Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get top N records using LINQ to Entities

I am using Linq to entities and would like to know if I can get a limited number of records when i query. I just need the top N records as the query do the orderby and other clauses. Is this possible or I will have to get the top N using foreach loop?

like image 908
Abdel Raoof Olakara Avatar asked May 20 '10 14:05

Abdel Raoof Olakara


People also ask

What is Linq to Entity in C#?

LINQ to Entities provides Language-Integrated Query (LINQ) support that enables developers to write queries against the Entity Framework conceptual model using Visual Basic or Visual C#. Queries against the Entity Framework are represented by command tree queries, which execute against the object context.

What is the difference between EF and Linq?

Entity Framework is an object-relational mapping (ORM) framework for connecting C# code to external databases, usually SQL Server. LINQ is a query language embedded into C# and a set of extension methods in order to make it useful.


2 Answers

There are multiple ways

1)

var data = (from p in db.people               orderby p.IdentityKey descending              select p).Take(100);  

2)

var query = db.Models.Take(100); 

3) or you can skip certain results

var data = (from p in people             select p).Skip(100); 
like image 66
Mohit Verma Avatar answered Sep 23 '22 19:09

Mohit Verma


You can just use the .Take method call to get a couple of result. You can read more on this topic here.

You need to understand that the query will not be executed unless someone executes the GetEnumerator().

like image 22
sovanesyan Avatar answered Sep 21 '22 19:09

sovanesyan