How to implement SkipWhile with Linq to Sql without first loading the whole list into memory?

前端 未结 3 1042
天命终不由人
天命终不由人 2021-01-17 12:05

I need to order the articles stored in a database by descending publication date and then take the first 20 records after the article with Id == 100.

T

相关标签:
3条回答
  • 2021-01-17 12:31

    If, as I'm guessing from the column name, PublicationDate doesn't change, you can do this in two separate queries:

    • Establish the PublicationDate of the Article with Id == 100
    • Retrieve the 20 articles from that date onwards

    Something like:

    var thresholdDate = db.Articles.Single(a => a.Id == 100).PublicationDate;
    var articles = 
        db.Articles
        .Where(a => a.PublicationDate <= thresholdDate)
        .OrderByDescending(a => a.PublicationDate)
        .Take(20);
    

    It might even be that LINQ to SQL can translate this:

    var articles = 
        db.Articles
        .Where(a => a.PublicationDate 
                 <= db.Articles.Single(aa => aa.Id == 100).PublicationDate)
        .OrderByDescending(a => a.PublicationDate)
        .Take(20);
    

    but that may be too complex for it. Try it and see.

    0 讨论(0)
  • 2021-01-17 12:39

    You can try like this

    var articles = 
        db.Articles
        .Where(a => a.PublicationDate < db.Articles
                                        .Where(aa => aa.Id==100)
                                        .Select(aa => aa.PublicationDate)
                                        .SingleOrDefault())
        .OrderByDescending(a => a.PublicationDate)
        .Take(20);
    
    0 讨论(0)
  • 2021-01-17 12:51

    Isnt the solution to just add a where statement?

    IQueryable<Article> articles = db.Articles.Where(a => a.id != 100).OrderByDescending(a => a.PublicationDate).Take(20);
    
    0 讨论(0)
提交回复
热议问题