EF 拉姆达 linq 帮助类
(这个类是很早以前在网上找的,忘记出处请原谅。)
一、基本用法
[Route("List")]
public ApiResult GetList(int page, int limit, string sort = null, string order = null, string filters = null, string query = null)
{
PageModel p = new PageModel();
if (filters != null)
{
p.filters = Newtonsoft.Json.JsonConvert.DeserializeObject<Filter[]>(filters);
}
p.page = page;
p.rows = limit;
p.sort = sort;
p.order = order;
)
{
p.page = ;
}
)
{
p.rows = ;
}
var data = manage.GetQueryable().Select(d => d);
//过滤
data = data.Where(p.filters);
//搜索条件
)
{
data = data.Where(new string[] { "UserName", "RealName" }, query);
}
//排序
if (order != "normal" && sort != null)
{
bool isAsc = order == "asc";
data = data.OrderBy(new[] { sort }, new[] { isAsc });
}
else
{
//默认排序
data = data.OrderBy(d => d.UserID);
}
DataModel pageData = new DataModel();
pageData.page = p.page;
pageData.total = data.Count();
pageData.rows = data.Skip((p.page - ) * p.rows).Take(p.rows).ToList();
ApiResult result = new ApiResult();
result.success = true;
result.data = pageData;
return result;
}
完整案例:结合前端 elementUI 组件 可以实现分页 查询、排序、过滤等。
https://www.cnblogs.com/hao-1234-1234/p/9647322.html#4225885
二、linq 帮助类
重写了where和orderby方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using Vegetable.Models;
namespace Vegetable.DAL
{
public static class QueryableExtension
{
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string[] propertyName, bool[] ascending) where T : class
{
Type type = typeof(T);
; i < propertyName.Length; i++)
{
PropertyInfo property = type.GetProperty(propertyName[i]);
if (property == null)
throw new ArgumentException("propertyName", "Not Exist");
ParameterExpression param = Expression.Parameter(type, "p");
Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
LambdaExpression orderByExpression = Expression.Lambda(propertyAccessExpression, param);
string methodName = ascending[i] ? "OrderBy" : "OrderByDescending";
)
{
methodName = ascending[i] ? "ThenBy" : "ThenByDescending";
}
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression));
source = source.Provider.CreateQuery<T>(resultExp);
}
return source;
}
public static IQueryable<T> Where<T>(this IQueryable<T> source, FilterRule[] filterRules) where T : class
{
if (filterRules == null)
{
return source;
}
Type type = typeof(T);
ParameterExpression param = Expression.Parameter(type, "c");
Expression<Func<T, bool>> op = null;
foreach (var rule in filterRules)
{
PropertyInfo property = type.GetProperty(rule.Field);
if (property == null)
{
continue;
}
//c.Field==Value
//c=>c.Field.Contains(Value)
Expression left = Expression.Property(param, property);
Expression right = Expression.Constant(rule.Value);
Type valueType = property.PropertyType;
if (rule.Value == null || rule.Value == "") continue;
DateTime inputDateTime = DateTime.Now;
try
{
if (valueType == typeof(int) || valueType == typeof(int?))
{
right = Expression.Constant(Convert.ToInt32(rule.Value.Split(]));
}
else if (valueType == typeof(short) || valueType == typeof(short?))
{
right = Expression.Constant(Convert.ToInt16(rule.Value.Split(]));
}
else if (valueType == typeof(byte) || valueType == typeof(byte?))
{
right = Expression.Constant(Convert.ToByte(rule.Value.Split(]));
}
else if (valueType == typeof(long) || valueType == typeof(long?))
{
right = Expression.Constant(Convert.ToInt64(rule.Value));
}
else if (valueType == typeof(float) || valueType == typeof(float?))
{
right = Expression.Constant(Convert.ToSingle(rule.Value));
}
else if (valueType == typeof(double) || valueType == typeof(double?))
{
right = Expression.Constant(Convert.ToDouble(rule.Value));
}
else if (valueType == typeof(decimal) || valueType == typeof(decimal?))
{
right = Expression.Constant(Convert.ToDecimal(rule.Value));
}
else if (valueType == typeof(DateTime) || valueType == typeof(DateTime?))
{
inputDateTime = Convert.ToDateTime(rule.Value);
right = Expression.Constant(Convert.ToDateTime(rule.Value));
}
else if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
right = Expression.Constant(Guid.Parse(rule.Value));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
Expression filter = Expression.Equal(left, right);
Expression filter2 = null;
MethodInfo method;
switch (rule.Op)
{
case OP.contains:
//BinaryExpression
if (valueType == typeof(string))
{
method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
filter = Expression.Call(left, method, right);
}
else if (valueType == typeof(DateTime) || valueType == typeof(DateTime?))
{
right = Expression.Constant(inputDateTime.Date);
filter = Expression.GreaterThanOrEqual(left, right);
right = Expression.Constant(inputDateTime.Date.AddDays());
filter2 = Expression.LessThan(left, right);
}
else
{
filter = Expression.Equal(left, right);
}
break;
case OP.equal:
filter = Expression.Equal(left, right);
break;
case OP.notequal:
filter = Expression.NotEqual(left, right);
break;
case OP.beginwith:
method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
filter = Expression.Call(left, method, right);
break;
case OP.endwith:
method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
filter = Expression.Call(left, method, right);
break;
case OP.less:
filter = Expression.LessThan(left, right);
break;
case OP.lessorequal:
filter = Expression.LessThanOrEqual(left, right);
break;
case OP.greater:
filter = Expression.GreaterThan(left, right);
break;
case OP.greaterorequal:
filter = Expression.GreaterThanOrEqual(left, right);
break;
default:
break;
}
var lambda = Expression.Lambda<Func<T, bool>>(filter, param);
if (op == null)
{
op = lambda;
}
else
{
op = Expression.Lambda<Func<T, bool>>(Expression.And(op.Body, lambda.Body), op.Parameters);
}
if (filter2 != null)
{
var lambda2 = Expression.Lambda<Func<T, bool>>(filter2, param);
op = Expression.Lambda<Func<T, bool>>(Expression.And(op.Body, lambda2.Body), op.Parameters);
}
}
if (op != null)
{
source = source.Where(op);
}
return source;
}
public static IQueryable<T> Where<T>(this IQueryable<T> source, Filter[] filters) where T : class
{
if (filters == null)
{
return source;
}
Type type = typeof(T);
ParameterExpression param = Expression.Parameter(type, "c");
Expression<Func<T, bool>> op = null;
foreach (var rule in filters)
{
PropertyInfo property = type.GetProperty(rule.Field);
if (property == null)
{
continue;
}
//c.Field==Value
//c=>(c.Field.Contains(Value) || c.Field.Contains(Value))
Exception outExc = new Exception();
Expression left = Expression.Property(param, property);
Type valueType = property.PropertyType;
) continue;
Expression<Func<T, bool>> lambdaOut = null;
foreach (var v in rule.Value)
{
Expression right = Expression.Constant(v);
DateTime inputDateTime = DateTime.Now;
try
{
if (valueType == typeof(int) || valueType == typeof(int?))
{
right = Expression.Constant(Convert.ToInt32(v.Split(]));
}
else if (valueType == typeof(short) || valueType == typeof(short?))
{
right = Expression.Constant(Convert.ToInt16(v.Split(]));
}
else if (valueType == typeof(byte) || valueType == typeof(byte?))
{
right = Expression.Constant(Convert.ToByte(v.Split(]));
}
else if (valueType == typeof(long) || valueType == typeof(long?))
{
right = Expression.Constant(Convert.ToInt64(v));
}
else if (valueType == typeof(float) || valueType == typeof(float?))
{
right = Expression.Constant(Convert.ToSingle(v));
}
else if (valueType == typeof(double) || valueType == typeof(double?))
{
right = Expression.Constant(Convert.ToDouble(v));
}
else if (valueType == typeof(decimal) || valueType == typeof(decimal?))
{
right = Expression.Constant(Convert.ToDecimal(v));
}
else if (valueType == typeof(DateTime) || valueType == typeof(DateTime?))
{
inputDateTime = Convert.ToDateTime(v);
right = Expression.Constant(Convert.ToDateTime(v));
}
else if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
right = Expression.Constant(Guid.Parse(v));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
Expression filter = Expression.Equal(left, right);
Expression filter2 = null;
MethodInfo method;
switch (rule.Op)
{
case OP.contains:
//BinaryExpression
if (valueType == typeof(string))
{
method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
filter = Expression.Call(left, method, right);
}
else if (valueType == typeof(DateTime) || valueType == typeof(DateTime?))
{
right = Expression.Constant(inputDateTime.Date);
filter = Expression.GreaterThanOrEqual(left, right);
right = Expression.Constant(inputDateTime.Date.AddDays());
filter2 = Expression.LessThan(left, right);
}
else
{
filter = Expression.Equal(left, right);
}
break;
case OP.equal:
filter = Expression.Equal(left, right);
break;
case OP.notequal:
filter = Expression.NotEqual(left, right);
break;
case OP.beginwith:
method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
filter = Expression.Call(left, method, right);
break;
case OP.endwith:
method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
filter = Expression.Call(left, method, right);
break;
case OP.less:
filter = Expression.LessThan(left, right);
break;
case OP.lessorequal:
filter = Expression.LessThanOrEqual(left, right);
break;
case OP.greater:
filter = Expression.GreaterThan(left, right);
break;
case OP.greaterorequal:
filter = Expression.GreaterThanOrEqual(left, right);
break;
default:
break;
}
var lambda = Expression.Lambda<Func<T, bool>>(filter, param);
if (lambdaOut == null)
{
lambdaOut = lambda;
}
else
{
lambdaOut = Expression.Lambda<Func<T, bool>>(Expression.Or(lambdaOut.Body, lambda.Body), lambdaOut.Parameters);
}
if (filter2 != null)
{
var lambda2 = Expression.Lambda<Func<T, bool>>(filter2, param);
lambdaOut = Expression.Lambda<Func<T, bool>>(Expression.And(lambdaOut.Body, lambda2.Body), lambdaOut.Parameters);
}
}
if (op == null)
{
op = lambdaOut;
}
else
{
op = Expression.Lambda<Func<T, bool>>(Expression.And(op.Body, lambdaOut.Body), op.Parameters);
}
}
if (op != null)
{
source = source.Where(op);
}
return source;
}
public static IQueryable<T> Where<T>(this IQueryable<T> source, string[] columnNames, string filterString)
{
Type type = typeof(T);
ParameterExpression param = Expression.Parameter(type, "c");
Expression right = Expression.Constant(filterString);
//1!=1
//Expression op = Expression.NotEqual(Expression.Constant(1), Expression.Constant(1));
Expression<Func<T, bool>> op = null;
foreach (var column in columnNames)
{
PropertyInfo property = type.GetProperty(column);
if (property == null)
{
continue;
}
//c.Field==Value
//c=>c.Field.Contains(Value)
Expression left = Expression.Property(param, property);
Type valueType = property.PropertyType;
if (valueType != typeof(string)) continue;
if (filterString == null || filterString == "") continue;
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
Expression filter = Expression.Call(left, method, right);
var lambda = Expression.Lambda<Func<T, bool>>(filter, param);
if (op == null)
{
op = lambda;
}
else
{
op = Expression.Lambda<Func<T, bool>>(Expression.Or(op.Body, lambda.Body), op.Parameters);
}
}
if (op != null)
{
source = source.Where(op);
}
return source;
}
}
}
EF 拉姆达 linq 帮助类的更多相关文章
- EF 拉姆达 linq if else (整理)
首先想到: var data0 = db.T_Plants2; //这里加.AsQueryable() ) { .Where(d => d.NaturalEcosystem == true); ...
- EF 拉姆达 动态拼接查询语句
EF 动态拼接查询语句 using System; using System.Collections.Generic; using System.IO; using System.Linq; usin ...
- C# 匿名方法和拉姆达表达式
有时候,我们需要封装一组数据,只有数据,没有方法,并且只用于当前程序,不需要在项目间重用,这时候,如果是传统的使用类来封装的话,大概会是下面这种样子: internal class SomeData ...
- C#进阶之路(四):拉姆达
对于拉姆达,许多文章都讲过原理及如何使用,所以这篇文章我主要是摘录我学习过的文字,总结下我自己的学习心得. 什么是拉姆达表达式 "Lambda表达式"是一个匿名函数,是一种高效的类 ...
- C#拉姆达(=>)表达式
前言: 之前小猪曾经分享过自己对C#委托的一点理解 其实在使用委托的过程中我们会大量的使用拉姆达(=>)表达式 介绍: "Lambda表达式"是一个匿名函数,是一种高效的类似 ...
- 如何用拉姆达表达式(Lambda Expressions) 书写左链接查询
在C#中,如果要实现两个列表的左链接查询,我们的一般用法就是用的linq表达式就是 List<Pet> pets = }, }, } }; List<Pet2> pets2 = ...
- SqlSugar常用查询实例-拉姆达表达式
SqlSugar支持拉姆达表达式查询,匿名对象参数等,相对还是比较方便好用的. 一.查询列表: //查询列表 SqlSugarClient db = SugarContext.GetInstance( ...
- (转)拉姆达表达式(Lambda Expressions) =>写法的涵义
lambdaclass编译器 让我们先看一个简单的拉姆达表达式: x=>x/2 这个表达式的意思是:x为参数,对x进行相应的操作后的结果作为返回值. 通过这个拉姆达表达式,我们可以看到: 这 ...
- Java8新特性(拉姆达表达式lambda)
一.函数式接口 函数式接口(functional interface 也叫功能性接口,其实是同一个东西).简单来说,函数式接口是只包含一个方法的接口.比如Java标准库中的java.lang.Runn ...
随机推荐
- 纯CSS制作加<div>制作动画版哆啦A梦
纯CSS代码加上<div>制作动画版哆啦A梦(机器猫) 哆啦A梦(机器猫)我们大家一定都很熟悉,今天给大家演示怎么用纯CSS代码,来做一个动画版的哆啦A梦. 效果图: ###下面代码同学可 ...
- Idea中maven项目中导入本地jar包
说一下正确的流程: 1.将jar包导入到本地maven库或者远程nexus仓库,再使用maven引用: 2.导入命令: //通过一下信息引入maven -DgroupId=com.test -Dart ...
- python的is与==的区别
is is比较的是两个变量的地址值,如果地址值正确,则返回True,否则返回False,实例如下: 如图所示,a,b列表的数值相等,但地址是不相等的,所以返回True,与值无关 == ==比较的是两个 ...
- Appium+python自动化(十六)- ADB命令,知否知否,应是必知必会(超详解)
简介 Android 调试桥(adb)是多种用途的工具,该工具可以帮助你你管理设备或模拟器 的状态. adb ( Android Debug Bridge)是一个通用命令行工具,其允许您与模拟器实例或 ...
- 仿写一个简陋的 IOC/AOP 框架 mini-spring
讲道理,感觉自己有点菜.Spring 源码看不懂,不想强行解释,等多积累些项目经验之后再看吧,但是 Spring 中的控制反转(IOC)和面向切面编程(AOP)思想很重要,为了更好的使用 Spring ...
- HTTP 学习笔记01
HTTP hypertext transfer protocol (超文本传输协议) TCP/IP 协议集中的一个应用层协议 用于定义WEB浏览器与WEB服务器之间交换数据的过程以及数据本身的格式 ...
- IntelliJ Idea 常用快捷键总结-0 #<间断性更新中...>,部分有示例
IntelliJ Idea 常用快捷键总结-0 <间断性更新中...>,部分有示例 自动补齐代码 常用的有for循环体,fori可以输出循环语句: eg: public void test ...
- Web前端——JavaScript扩展补充
JS补充 document也是windows的一个子对象 a标签点击事件 要想设置点击a标签,执行某种方法,推荐在a标签的herf属性使用JavaScript伪协议,实现点击之后执行的js方法,而不是 ...
- C# 管道式编程
受 F# 中的管道运算符和 C# 中的 LINQ 语法,管道式编程为 C# 提供了更加灵活性的功能性编程.通过使用 扩展函数 可以将多个功能连接起来构建成一个管道. 前言 在 C# 编程中,管道式编程 ...
- Spring Boot 2.x (十八):邮件服务一文打尽
前景介绍 在日常的工作中,我们经常会用到邮件服务,比如发送验证码,找回密码确认,注册时邮件验证等,所以今天在这里进行邮件服务的一些操作. 大致思路 我们要做的其实就是把Java程序作为一个客户端,然后 ...