简体   繁体   中英

ASP.NET MVC 4.5 Linq Query for PagedList

I'm currently working on an ASP.NET MVC 4.5 application. I have one question for the Linq Gurus please.

I want to use the .Where Filter only if the importing parameter initOfferList = false . The problem: the PagedList gets only filtered for the first page (10 entries here).

My Linq query looks as follows:

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;  
}

How can I modify my query to properly use the .Where clause on all entries, but only when the importing parameter initOfferList = false ?

Thank you!

Try:

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;
}

If I understand correctly, the following should take your boolean flag into account in a single Linq, thus applying the where to the full list before filtering.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM