我有一个LINQ查询:

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

如何修改此查询以从数据库中只选择五个结果?


当前回答

解决方案:

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

其他回答

额外的信息

有时需要将模型绑定到视图模型,并给出类型转换错误。在这种情况下,您应该使用ToList()方法。

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

解决方案:

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

这也可以使用Linq的基于Lambda的方法来实现;

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

[提供了一个比@Ajni提供的答案更具描述性的答案。]

这也可以通过使用LINQ流利语法实现:

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

注意,这个LINQ语句中出现的每个方法(Where、OrderBy、Take)都以lambda表达式作为参数。还要注意Enumerable的文档。Take开始于:

类的开头返回指定数目的连续元素 序列。