首先简单地完善一下前面提到的例子,代码如下:
- 测试实体类
//测试实体类
public class Table
{
public int A;
public int B;
}
- 独立条件类
//独立条件:
public class Field
{
public Logical Logical { get; set; } //与其它条件之间的逻辑关系
public Comparer Comparer { get; set; } //条件比较符
public Type DataType { get; set; } //数据类型
public string FieldName { get; set; } //字段名称
public object QueryValue { get; set; } //条件值
}
- 条件组类
//条件组:
public class Block
{
public Logical Logical { get; set; } //与其它条件组或独立条件之间的逻辑关系
public List Fields { get; set;}=new List();
public List Blocks { get;set; }=new List();
}
- 枚举
//逻辑
public enum Logical
{
And,
Or,
}
//比较
public enum Comparer
{
Equal,
GreatThan,
LessThan,
}
代码简单就不作多说明了,就是添加一个独立条件,两个子组,子组里分别包含两个独立条件,以描述等效于
SQL
=(Table1.A5 And Table1.B=3)) OR Table1.B>5
的查询子句。
Block CreaterDescriptor()
{
//SQL: (Table1.A5 And Table1.B=3)) OR Table1.B>5
var block = new Block() {Logical= Logical.Or};
block.Fields.AddRange(new[]{new Field(){ Comparer= Comparer.GreatThan, DataType= typeof(int), FieldName="B", Logical= Logical.Or, QueryValue=5}});
block.Blocks.AddRange(new [] {
new Block(){
Logical= Logical.Or,
Fields=new List(new Field[]{
new Field(){ Comparer= Comparer.LessThan, DataType=typeof(int), FieldName="A", QueryValue= 3},
new Field(){ Comparer= Comparer.Equal, DataType=typeof(int), FieldName="A", Logical= Logical.Or, QueryValue= 3}
}),
},
new Block(){
Logical= Logical.Or,
Fields=new List(new Field[]{
new Field(){ Comparer= Comparer.GreatThan, DataType=typeof(int), FieldName="A", QueryValue= 5},
new Field(){ Comparer= Comparer.Equal, DataType=typeof(int), FieldName="B", Logical= Logical.And,QueryValue= 3}
}),
},
});
return block;
}
至此,已经拿到查询条件描述对象,知道了需要以什么条件进行查询了,一下步就是如何其转换为查询委托。
先来个手动组装看看上篇的设想能不能行得通。
Expression> Manual()
{
//SQL: (Table1.A5 And Table1.B=3)) OR Table1.B>5
//老套路,先包装
var Table1 = new Table();
var p = Expression.Parameter(typeof(Table), "Table1");
//将5、3这两个常量包装成ConstantExpression:
var num5 = Expression.Constant(5, typeof(int));
var num3 = Expression.Constant(3, typeof(int));
//将两个属性包装成MemberExpression。
var a = Expression.PropertyOrField(p, "A");
var b = Expression.PropertyOrField(p, "B");
//构造Table1.A5:
var gtA5 = Expression.GreaterThan(a, num5);
//构造Table1.A=5:
var eqB3 = Expression.Equal(b, num3);
//构造Table1.B>5:
var gtB5 = Expression.GreaterThan(b, num5);
//构造Table1.A5 && Table1.B=3
var expGtA5andEqB3 = Expression.AndAlso(gtA5, eqB3);
//构造(Table1.A5 And Table1.B=3))
var expGtA5andEqA3_Or_expLtA3orEqA3=Expression.OrElse(expLtA3orEqA3,expGtA5andEqB3);
//(Table1.A5 And Table1.B=3)) OR Table1.B>5
var result=Expression.OrElse(expGtA5andEqA3_Or_expLtA3orEqA3,gtB5);
//结果要出来了
Expression> lambda=Expression.Lambda>(result,p);
return lambda;
}
手动组装好了,来测试验证一下:
//测试方法
void TestLambda(Expression> lambda)
{
var list = new List
{
new Table{A=6,B=2},
new Table{A=5,B=6},
new Table{A=2,B=3}
}
;
var my = list.Where(t => lambda.Compile()(t)).ToArray();
var linq = list.Where(t => ((t.A 5 && t.B == 3)) || t.B > 5).ToArray();
Debug.Assert(my.Length == linq.Length);
for (var i = 0; i
//运行测试
void Main()
{
var lambda=Manual();
TestLambda(lambda );
}
经过上机运行,结果正确,OK!
但是,问题来了,这手动组装并不简单,稍不留神就容易写错,如果真这么用,就是浪费表情了。那么有没有自动的,不需要人工干预的方法?必须有,否则本系列文章还有什么可写的呢?
具体看下面代码,就不太过啰嗦的解释了,简单说明一下思路,拿到一个多层嵌套的条件组之后,先对直接的独立条件进行LambdaExpression逐个组装,串联起来,再逐个组装子条件组也串联起来,最后把独立条件和子组串联起来,如果子组里还有子组,进行逐层递归:
Expression> CreaterQueryExpression(Block block)
{
var param=Expression.Parameter(typeof(T),typeof(T).Name);
return Expression.Lambda>(CreateBlockExpr(block),param);
Expression CreateFieldExpr(List fields)
{
var lastExp=default(Expression);
foreach (var f in fields)
{
var member=Expression.PropertyOrField(param, f.FieldName);
var value=Expression.Constant(f.QueryValue);
var exp=f.Comparer switch
{
Comparer.GreatThan=>Expression.GreaterThan(member,value),
Comparer.LessThan=>Expression.LessThan(member,value),
_=> Expression.Equal(member,value),
};
if (lastExp != default(Expression))
{
exp= f.Logical switch
{
Logical.Or => Expression.OrElse(lastExp,exp),
_=>Expression.AndAlso(lastExp,exp),
};
}
lastExp=exp;
}
return lastExp;
}
Expression CreateBlockExpr(Block block)
{
var lastExp=default(Expression);
var exp=CreateFieldExpr(block.Fields);
foreach (var sub in block.Blocks)
{
var subExp = CreateBlockExpr(sub);
if (lastExp != default && subExp!=default)
{
subExp = sub.Logical switch
{
Logical.Or => Expression.OrElse(lastExp, subExp),
_ => Expression.AndAlso(lastExp, subExp),
};
}
lastExp=subExp;
}
if (lastExp != default && exp!=default)
{
exp= block.Logical switch
{
Logical.Or => Expression.OrElse(exp, lastExp),
_ => Expression.AndAlso(exp, lastExp),
};
}
return exp;
}
}
好,委托已经拿到。是否能正确实现查询意图呢?来测试一下:
// 运行测试
void Main()
{
var lambda=CreaterQueryExpression(CreaterDescriptor());
TestLambda(lambda);
}
经上机运行,结果OK!
- 至此,初步的原型实现已经完成.
- 接下来要做什么呢,是正式编码开战呢,还是思考一下,有什么应用场景,有什么优缺点,如果有缺点能不能克服?如果正式开战可能会遇到些什么问题或困难,要如何解决?
- 敬请等下回分解,随手点个赞呗。
posted @
2023-05-27 19:40
Tongze
阅读(70)
评论(3)
编辑
收藏
举报
var cb_entryId = 17437225, cb_entryCreatedDate = '2023-05-27 19:40', cb_postType = 1, cb_postTitle = '基于Expression Lambda表达式树的通用复杂动态查询构建器——《原型篇一》[已开源]';
var allowComments = true, cb_blogId = 793229, cb_blogApp = 'ls0001', cb_blogUserGuid = 'a7d01616-edf2-df11-ac81-842b2b196315';
mermaidRender.render()
markdown_highlight()
zoomManager.apply("#cnblogs_post_body img:not(.code_img_closed):not(.code_img_opened)");
updatePostStats(
[cb_entryId],
function(id, count) { $("#post_view_count").text(count) },
function(id, count) { $("#post_comment_count").text(count) });
var commentManager = new blogCommentManager();
commentManager.renderComments(0);
fixPostBody();
window.footnoteTipManager.generateFootnoteTips();
window.tocManager.displayDisableTocTips = false;
window.tocManager.generateToc();
setTimeout(function() { countViews(cb_blogId, cb_entryId); }, 50);
deliverT2();
deliverC1C2();
loadNewsAndKb();
LoadPostCategoriesTags(cb_blogId, cb_entryId);
LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate, cb_postType);
loadOptUnderPost();
GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);
loadBlogSideColumn();
loadBlogDefaultCalendar();
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
var kv = getGACustom();
if (kv) {
gtag('set', kv);
}
gtag('config', 'UA-476124-1');
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
如何使用Blazor在Linux平台下运行Desktop程序 本文将讲解如何使用Blazor运行跨平台应用,应用到的技术有以下几点 Blazor Masa Blazor Photino.Blazor Ubuntu 用于验证跨平台性,并且是否提高开发效率,Bla…