简体   繁体   English

如何从lambda表达式中获取唯一字符串

[英]How to get unique string from a lambda expression

I would like to cache a EF4 result using a generic repository & memcached. 我想使用通用存储库和memcached缓存EF4结果。 This all works great, except for the fact that I need a unique key representation for a lambda expression. 这一切都很有效,除了我需要一个lambda表达式的唯一键表示。

For example a call to the generic repository could be: 例如,对通用存储库的调用可以是:

Repository<User> userRepository = new Repository<User>();
string name = "Erik";
List<User> users_named_erik = userRepository.Find(x => x.Name == name).ToList();

In my generic repository function I need to make a unique key out of the lambda expression to store it in memcached. 在我的通用存储库函数中,我需要从lambda表达式中创建一个唯一的键,以将其存储在memcached中。

So I need a function that can do this 所以我需要一个可以做到这一点的功能

string GetPredicate(Expression<Func<T,bool>> where)
{

}

The result of the function should be this string x=> x.Name == "Erik" . 函数的结果应该是这个字符串x=> x.Name == "Erik" And not something like +<>c__DisplayClass0) which I get from the ToString() method. 而不是像我从ToString()方法得到的+<>c__DisplayClass0)

Thanks in advance. 提前致谢。

Take a look at this blog entry . 看看这篇博客文章

Basically, you're looking to do a "Partial Evaluation" of the expression to account for the value introduced by the closure. 基本上,您希望对表达式进行“部分评估”以考虑闭包引入的值。 This MSDN Walkthrough (under the heading "Adding the Expression Evaluator") has the code that is referenced by the blog entry for incorporating the unevaluated closure members in the resulting string. MSDN演练 (在“添加表达式评估程序”标题下)具有博客条目引用的代码,用于将未评估的闭包成员合并到结果字符串中。

Now, it may not work with complex expressions, but it looks like it will get you on your way. 现在,它可能不适用于复杂的表达式,但看起来它会让你在路上。 Just keep in mind that it doesn't normalize expressions. 请记住,它没有规范化表达式。 That is x => x.Name == "Erik" is functionally equivalent to x => "Erik" == x.Name (and all other variants). x => x.Name == "Erik"在功能上等同于x => "Erik" == x.Name (以及所有其他变体)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM