C#扩展列表 对于DateTime属性之一

问题描述 投票:1回答:1

我有一个带有过滤器选项的网站,当客户发布请求时,我会检查过滤器属性是否有价值,如果有,则执行过滤工作:

public async Task<IActionResult> ContentTable(ContentTableViewModel vm)
{
    vm = vm == null ? new ContentTableViewModel() : vm;
    var qList = _service.Get(); //IQueryable

    if (vm.From.HasValue)
        qList = qList.Where(x => x.Date >= vm.From.Value);
    if(vm.PlanTo.HasValue)
    {
        vm.PlanTo = vm.To.Value.AddDays(1);
        qList = qList.Where(x => x.Date < vm.To.Value);
    }
    vm.List = await qList.ToListAsync();
    return View(vm);
}

我经常使用它,这就是为什么我想使用“ From”和“ To”作为方法参数并为过滤器列表返回List的扩展方法。 重要还将告诉扩展方法哪个属性将被过滤-在这种情况下,[[日期

public static void WhereBetweenDates<T>(this IList<T> list, DateTime from, DateTime to) { //? list has no property }
我是否需要每个T具有BaseClass?告诉方法“哪里T:基本”?
c# list extension-methods
1个回答
3
投票
public static void WhereBetweenDates<T>(this IList<T> list, DateTime from, DateTime to, Func<T, DateTime> extractor) { foreach (var element in list) { var elementDt = extractor(element); if (elementDt > from && elementDt < to) { // accept element } } }
© www.soinside.com 2019 - 2024. All rights reserved.