109221793
109221793

Reputation: 16887

LINQ query to select top five

I have a LINQ query:

var list = from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t;

How can I modify this query to select just five results from the database?

Upvotes: 280

Views: 440574

Answers (6)

maoyang
maoyang

Reputation: 1095

I am just thinking you might be feel unfamiliar with the sequence From->Where->Select, as in an SQL script, it is like Select->From->Where.

But you may not know that inside the SQL engine, it is also parsing in the sequence of 'From->Where->Select'. To validate it, you can try a simple script,

select id as i from table where i=3

and it will not work. The reason is the engine will parse Where before Select, so it won't know alias i in the where. To make this work, you can try

select * from (select id as i from table) as t where i = 3

Upvotes: 2

DavidRR
DavidRR

Reputation: 19397

This can also be achieved using LINQ fluent syntax:

var list = ctn.Items
    .Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
    .OrderBy(t => t.Delivery.SubmissionDate)
    .Take(5);

Note that each method (Where, OrderBy, Take) that appears in this LINQ statement takes a lambda expression as an argument. Also note that the documentation for Enumerable.Take begins with:

Returns a specified number of contiguous elements from the start of a sequence.

(This is offering a somewhat more descriptive answer than the answer provided by Ajni.)

Upvotes: 13

Anji
Anji

Reputation: 311

This can also be achieved using the lambda-based approach of LINQ;

var list = ctn.Items
             .Where(t => t.DeliverySelection == true &&
                    t.Delivery.SentForDelivery == null)
             .OrderBy(t => t.Delivery.SubmissionDate)
             .Take(5);

Upvotes: 28

topcool
topcool

Reputation: 2720

Additional information

Sometimes it is necessary to bind a model into a view models and give a type conversion error. In this situation you should use ToList() method.

var list = (from t in ctn.Items
       where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
       orderby t.Delivery.SubmissionDate
       select t).Take(5).ToList();

Upvotes: 8

Harold Sota
Harold Sota

Reputation: 7566

The solution:

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

Upvotes: 45

Gideon
Gideon

Reputation: 18491

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

Upvotes: 510

Related Questions