Linq表达式树字符串比较
问题描述:
我想构建一个表达式树来对字符串数组进行操作。我需要弄清楚如何使用Equal方法。Linq表达式树字符串比较
任何人都可以给我的使用Expression.Equal(或.Equals)方法为一个字符串比较恒定
1)的示例,并且
2)使用任何种类的表达使用的字符串。包含()方法用于过滤目的。
我想学习表达式树的力学,但截至目前为止,我还没有找到一个好的教程。我非常感谢你的帮助。
string[] arr = {"s1","s2","s3"};
IQueryable<String> queryableData = arr.AsQueryable<string>();
// what should go below here?
ParameterExpression p1 = Expression.Parameter(typeof(string), "c");
Expression left = Expression.Constant("s2");
Expression e1 = Expression.Equal(left, p1);
IQueryable<string> res = queryableData.Provider.CreateQuery<string>(e2);
答
啊哈,我看你问什么...而你真的进入了一些非常阴暗的水域,在.NET反射库不漂亮与之合作的少数领域之一。你必须创建一个调用表达式来调用queryableData对象上的Queryable.Where(),并使用该表达式创建一个新的查询......问题是,在.NET中获取一个通用版本的方法不一定是最简单的你曾经在你的生活中运行整个事情:
MethodCallExpression call = Expression.Call(
null, // Calling Queryable.Where(), extension method, not instance method
getGenericMethod<string>(typeof(Queryable), "Where", typeof(IQueryable<string>), typeof(Expression<Func<string,bool>>)),
Expression.Constant(queryableData),
Expression.Lamda(
e1,
p1)
);
IQueryable<string> res = queryableData.Provider.CreateQuery<string>(call);
你也必须定义getGenericMethod(你可以找到这个网上其他地方更好的实现中,这真的是相当简单的方法):
private static MethodInfo getGenericMethod<T>(Type type, string name, params Type[] paramTypes)
{
MethodInfo[] methods = type.GetMethods(name);
foreach(MethodInfo mi in methods)
{
if(!mi.IsGenericMethodDefinition) // or some similar property
continue;
if(mi.GetGenericArguments().Length != 1)
continue;
if(mi.GetParameters().Length != paramTypes.Length)
continue;
MethodInfo genMethod = mi.MakeGenericMethod(new Type[]{typeof(T)});
var ps = genMethod.GetParameters();
bool isGood = true;
for(int i = 0; i < ps.Length; i++)
{
if(ps[i].ParameterType != paramTypes[i])
{
isGood = false;
break;
}
}
if(isGood)
return genMethod;
}
return null;
}
那里几乎没有错误,但我希望你能看到从那里去哪里...
+0
感谢您的帮助。 – Sako73 2009-12-14 13:18:12
答
只给我的解决方案:
string[] arr = {"s1","s2","s3"};
IQueryable<String> queryableData = arr.AsQueryable<string>();
ParameterExpression pe = Expression.Parameter(typeof(string), "company");
Expression right = Expression.Constant("on");
Expression left = Expression.Call(pe, typeof(string).GetMethod("Contains"), right);
MethodCallExpression e2 = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { queryableData.ElementType },
queryableData.Expression,
Expression.Lambda<Func<string, bool>>(left, new ParameterExpression[] { pe }));
IQueryable<string> res = queryableData.Provider.CreateQuery<string>(e2);
你以及在正确的轨道上......什么来之后比较肯定是关于需求构造LINQ表达式的至少一部分直观。希望我的回答有点帮助... – LorenVS 2009-12-11 20:57:53