• C#根据日期范围过滤IQueryable<T>集合


    需要扩展IQueryable<T>,参数包括一个DateTime类型的属性、开始日期、截止日期。

        public static class MyExtension
        {
            public static IQueryable<T> WhereDateRange<T>(this IQueryable<T> source, Expression<Func<T, DateTime>> getter, DateTime from, DateTime to)
            {
                Expression body = getter.Body;
                var predicate = Expression.Lambda<Func<T, bool>>(
                    Expression.And(Expression.GreaterThanOrEqual(body, Expression.Constant(from)),Expression.LessThanOrEqual(body, Expression.Constant(to))),
                    getter.Parameters
                );
                return source.Where(predicate);
            }
        }

    现在可以筛选满足某个日期范围内的集合。比如:

        class Program
        {
            static void Main(string[] args)
            {
                IEnumerable<Pet> pets = new List<Pet>
                {
                    new Pet {Id=1,Birthday=new DateTime(2014,1,2) },
                    new Pet {Id=2,Birthday=new DateTime(2015,1,2) },
                    new Pet {Id=1,Birthday=new DateTime(2016,1,2) }
                };
    
                var query = pets.AsQueryable().WhereDateRange<Pet>(t => t.Birthday,DateTime.Now.AddYears(-2), DateTime.Now.AddYears(-1));
    
                foreach(var item in query)
                {
                    Console.WriteLine(item.Birthday.ToShortDateString());
                }
            }
        }
    
        public class Pet
        {
            public int Id { get; set; }
            public DateTime Birthday { get; set; }
        }
  • 相关阅读:
    python习题一
    华为区块链平台
    百度超级链 [Xuperchain]
    $$$Fabric v1.0 block结构与修改
    搭建 Hyperladger Fabric 基本流程
    python开发区块链【公有链】
    Asp.Net中WebServices的调用方式
    关于vs08生成解决方案慢的解决方法
    vs项目启动调试时,显示找不到文件问题
    新的公司
  • 原文地址:https://www.cnblogs.com/darrenji/p/5383296.html
Copyright © 2020-2023  润新知