1. 程式人生 > 實用技巧 >C# DataTable 使用linq 動態拼接查詢

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