[c#] 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?

This question is related to c# linq

The answer is


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);

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();

Just thinking you might be feel unfamiliar of the sequence From->Where->Select, as in sql script, it is like Select->From->Where.

But you may not know that inside Sql Engine, it is also parse 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 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

[Offering a somewhat more descriptive answer than the answer provided by @Ajni.]

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 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);