如何过滤IQueryable?

时间:2019-10-03 15:53:06

标签: c# linq

我有以下控制器:

public class EventsController : Controller
{
    private readonly ICustomerEventRepository _customerEventRepository;

    public EventsController(ICustomerEventRepository customerEventRepository)
    {
        _customerEventRepository = customerEventRepository;
    }

    public IActionResult Index(int? customerid, int? pageNumber, string code = "")
    {
        IQueryable<CustomerEvent> customerEvents;

        if (customerid.HasValue)
        {
            customerEvents =
                _customerEventRepository.CustomerEvents.Where(x => x.Customer.CustomerId == customerid)
                    .Include(x => x.Customer).OrderByDescending(x => x.CustomerEventId);
        }
        else if (!string.IsNullOrEmpty(code))
        {
            customerEvents =
                _customerEventRepository.CustomerEvents.Where(x => x.EventType == code)
                    .Include(x => x.Customer).OrderByDescending(x => x.CustomerEventId);
        }
        else
        {
            customerEvents = _customerEventRepository.CustomerEvents
                .Include(x => x.Customer).OrderByDescending(x => x.CustomerEventId);
        }

        var page = pageNumber ?? 1;

        var onePageOfEvents = customerEvents.ToPagedList(page, 15);

        return View(onePageOfEvents);
    }
}

请注意

_customerEventRepository = customerEventRepository;

是我的存储库。它从my返回IQueryable。在方法Index的签名中,我有一组参数。它是用于过滤的查询参数。现在我有2个(pageNumber不是过滤器参数,用于分页),但是我正在计划更多。所以这段代码不是很理想。如果我有更多的过滤器参数,我将被迫做出越来越多的if指令。因为条件不适用于LINQ。也许有人遇到过同样的问题?感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

如果我对您的理解正确,则希望基于多个条件构建查询。

IQueryable将执行推迟到实现该集合为止(例如,调用ToList或遍历该集合)。

这使您可以逐步构建查询。请参见下面的示例。

IQueryable<CustomerEvent> customerEvents = _customerEventRepository
                                               .CustomerEvents
                                               .Include(x => x.Customer);

if (customerid.HasValue)
{
    customerEvents = customerEvents.Where(x => x.Customer.CustomerId == customerid);
}

if (!string.IsNullOrEmpty(code))
{
    customerEvents = customerEvents.Where(x => x.EventType == code); 
}
// other conditions
...

// finally (this is when the query is actually executed)
var onePageOfEvents = customerEvents
                         .OrderByDescending(x => x.CustomerEventId)
                         .ToPagedList(page, 15);

return View(onePageOfEvents);