• QueryableHelper


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Text;
    
    namespace Oyang.Tool
    {
        public class QueryableHelper
        {
            public static IQueryable<TSource> WhereIf<TSource>(IQueryable<TSource> source, bool isTrue, Expression<Func<TSource, bool>> predicate)
            {
                if (isTrue)
                {
                    source = source.Provider.CreateQuery<TSource>(
                    Expression.Call(
                        null,
                        Where_TSource_2(typeof(TSource)),
                        source.Expression, Expression.Quote(predicate)
                        ));
                }
                return source;
            }
    
            private static MethodInfo s_Where_TSource_2;
    
            private static MethodInfo Where_TSource_2(Type TSource) =>
                 (s_Where_TSource_2 ??
                 (s_Where_TSource_2 = new Func<IQueryable<object>, Expression<Func<object, bool>>, IQueryable<object>>(Queryable.Where).GetMethodInfo().GetGenericMethodDefinition()))
                  .MakeGenericMethod(TSource);
    
            public static List<TSource> ToPageList<TSource>(IQueryable<TSource> source, ref int pageIndex, int pageSize, string sortField, bool isAsc, out int totalCount)
            {
                totalCount = source.Count();
                int pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
                if (pageCount > 0 && pageIndex > pageCount)
                {
                    pageIndex = pageCount;
                }
    
                var param = Expression.Parameter(typeof(TSource));
                var body = Expression.Property(param, sortField);
                dynamic keySelector = Expression.Lambda(body, param);
                source = isAsc ? Queryable.OrderBy(source, keySelector) : Queryable.OrderByDescending(source, keySelector);
                source = source.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return source.ToList();
            }
    
            public static List<TSource> ToPageList<TSource>(IQueryable<TSource> source, IPagination p)
            {
                int pageIndex = p.PageIndex;
                List<TSource> temp = ToPageList<TSource>(source, ref pageIndex, p.PageSize, p.SortField, p.IsAsc, out int totalCount);
                p.TotalCount = totalCount;
                p.PageIndex = pageIndex;
                return temp;
            }
        }
    }
  • 相关阅读:
    e870. 获取默认外观的数据
    e867. 获取和设置外观
    e776. 设置JList组件项的提示语
    e775. 设置JList组件项的维数
    e781. 设置JList中的选择模式
    e784. 监听对JList选择变动
    e780. 设置JList中的已选项
    e782. 排列JList中的项
    e779. 获得JList中的已选项
    e777. 获得JList组件的所有项
  • 原文地址:https://www.cnblogs.com/oyang168/p/9957340.html
Copyright © 2020-2023  润新知