C#根據日期範圍過濾IQueryable集合

 

須要擴展IQueryable<T>,參數包括一個DateTime類型的屬性、開始日期、截止日期。this

 

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

 

如今能夠篩選知足某個日期範圍內的集合。好比:spa

 

    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; }
    }
相關文章
相關標籤/搜索