Problem
I’ve got 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 change this query such that only five results from the database are returned?
Asked by 109221793
Solution #1
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5);
Answered by Gideon
Solution #2
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);
Answered by Harold Sota
Solution #3
Linq’s Lambda-based technique can likewise be used to accomplish this.
var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);
Answered by Anji
Solution #4
[Offering a somewhat more descriptive response than @Ajni’s.]
This is also possible with 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, have a look at the Enumerable documentation. Take begins with:
Answered by DavidRR
Solution #5
Additional information
Binding a model to a view model and returning a type conversion error is sometimes essential. In this case, the ToList() method should be used.
var list = (from t in ctn.Items
where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
orderby t.Delivery.SubmissionDate
select t).Take(5).ToList();
Answered by topcool
Post is based on https://stackoverflow.com/questions/4872946/linq-query-to-select-top-five