LINQ query to select top five

后端 未结 6 1182
轻奢々
轻奢々 2020-12-02 05:46

I have a LINQ query:

var list = from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           ord         


        
相关标签:
6条回答
  • 2020-12-02 06:20

    [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.

    0 讨论(0)
  • 2020-12-02 06:24
    var list = (from t in ctn.Items
               where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
               orderby t.Delivery.SubmissionDate
               select t).Take(5);
    
    0 讨论(0)
  • 2020-12-02 06:26

    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();
    
    0 讨论(0)
  • 2020-12-02 06:32

    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
    
    0 讨论(0)
  • 2020-12-02 06:39

    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);
    
    0 讨论(0)
  • 2020-12-02 06:45

    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);
    
    0 讨论(0)
提交回复
热议问题