簡體   English   中英

ASP.NET MVC 4.5 Linq查詢PagedList

[英]ASP.NET MVC 4.5 Linq Query for PagedList

我目前正在研究ASP.NET MVC 4.5應用程序。 我對Linq Gurus有一個問題。

我只想在導入參數initOfferList = false使用.Where篩選器。 問題:PagedList僅針對第一頁(此處為10個條目)進行過濾。

我的Linq查詢如下所示:

public IPagedList<OfferListVM> GetOfferList(OfferDateSearchVM offerDateSearch, bool initOfferList, int page)
{  
    var offerList = Db.Offer
         .Select(x => new OfferListVM
         {
             OfferId = x.OfferId,
             CreatedDate = x.CreatedDate,
             Label = x.OfferData.Label,
         })
        .OrderBy(x => x.OfferId)
        .ToPagedList(page, 10);

    if (!initOfferList)
    {
        offerList = offerList
            .Where(x => x.CreatedDate >= offerDateSearch.FromDate && x.CreatedDate <= offerDateSearch.ToDate)
            .OrderBy(x => x.OfferId)
            .ToPagedList(page, 10);
    }

    return offerList;  
}

如何修改查詢以在所有條目上正確使用.Where子句,但僅當導入參數initOfferList = false

謝謝!

嘗試:

public IPagedList<OfferListVM> GetOfferList(OfferDateSearchVM offerDateSearch, bool initOfferList, int page)
{

     var offerListQuery = Db.Offer.OrderBy(x => x.OfferId);

     if (!initOfferList)
     {
            offerListQuery = offerListQuery
                 .Where(x => x.CreatedDate >= offerDateSearch.FromDate &&
                 x.CreatedDate <= offerDateSearch.ToDate
              );                     
     }
     var offerList = offerListQuery
            .Select(x => new OfferListVM
            {
                OfferId = x.OfferId,
                CreatedDate = x.CreatedDate,
                Label = x.OfferData.Label,
            })
            .ToPagedList(page, 10);

        return offerList;
}

如果我理解正確,則以下內容應在單個Linq中考慮您的布爾標志,從而在過濾之前將where應用於完整列表。

var offerList = Db.Offer
             .Where(x => initOfferList == true || (initOfferList == false && x.CreatedDate >= offerDateSearch.FromDate && x.CreatedDate <= offerDateSearch.ToDate))
             .Select(x => new OfferListVM
             {
                 OfferId = x.OfferId,
                 CreatedDate = x.CreatedDate,
                 Label = x.OfferData.Label,
             })
            .OrderBy(x => x.OfferId)
            .ToPagedList(page, 10);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM