QueryableHelper

Posted oyang168

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
        }
    }
}

 

以上是关于QueryableHelper的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板

VSCode自定义代码片段6——CSS选择器

VSCode自定义代码片段——声明函数