C# DataTable 使用linq 动态拼接查询
//动态拼接多个参数,可以更加条件重新更改
//typeof(string)是数据类型
private static Func<DataRow, bool> ExoerssionCondition(DataRow dr, List<CompareConfig> columnList)
{ ParameterExpression r = Expression.Parameter(typeof(DataRow), "r"); //DataRow参数:r Expression con = Expression.Constant(true); //All nested conditions foreach (var item in columnList) { ConstantExpression expFieldName = Expression.Constant(item.TargetField, typeof(string)); //"Height" 字符串常量 ConstantExpression expValue= Expression.Constant(dr[item.SourceField].ToString(), typeof(string));//创建float常量5.0 } List<Expression> list = new List<Expression>(); list.Add(r); list.Add(expFieldName); //参数列表:DataRow, "Height" MethodInfo mi = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(string) }).MakeGenericMethod(typeof(string)); MethodCallExpression MC = Expression.Call(null, mi, list); //创建MethodCallExpression Expression SingleExpCon = Expression.Equal(MC, expValue); con = Expression.And(con, SingleExpCon); } var expLam = Expression.Lambda<Func<DataRow, bool>>(con, r); return expLam.Compile(); }
参考例子:https://blog.csdn.net/alai7150/article/details/103086231