简体   繁体   English

使用像Func这样的表达式

[英]Use Expression like Func

I need to get selector using expression which has source and destination, like mapper (I need it for EF). 我需要使用具有源和目标的表达式来获取选择器,例如mapper(对于EF我需要它)。

public class Region
{
    public int RegionId { get; set; }
    public string RegionName { get; set; }
}

var country = new List<Region> { new Region { RegionId = 21, RegionName = "MyRegion" } };
Expression<Func<Region, string>> exp = (x => x.RegionName);
country.Select(s => exp(s));
// exp(s) gives compilation error (Method name expected)

Is it possible to get it? 有可能得到吗?

Imagine this: 想象一下:

var items = new List<int>();
Expression<Func<int, int>> selector = (x => x);

You cannot do this because it is an Expression : 您不能这样做,因为它是一个Expression

selector(x); // will not work

But this will work because you are compiling the expression so now you can call the Func<int, int> : 但这将起作用,因为您正在编译表达式,因此现在可以调用Func<int, int>

selector.Compile()(1);

And if you want to use the expression in a IQueryable , you can do this: 如果要在IQueryable使用表达式,则可以执行以下操作:

items.AsQueryable().Select(x => selector);
// Or simply
items.AsQueryable().Select(selector);

So in your case, it should be: 因此,在您的情况下,应为:

country.Select(exp);

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

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