问题描述
我有一个Expression,可以将一种类型的对象转换为另一种类型.表达式如下:
I have an Expression that converts one type of object to another type. The expression is as follows:
public Expression<Func<SQLRepository.ActionType, Model.ActionType>> DBActionTypeToActionType =
(SQLRepository.ActionType at) => new Model.ActionType()
{
ID = at.OID,
DisplayName = at.DisplayName
};
我可以这样使用表达式:
I can use the Expression like this:
var linq = (from at in dc.SQLRepositoryDC.ActionTypes select at).Select(DBActionTypeToActionType);
但是我想这样使用它:
var linq = (from at in dc.SQLRepositoryDC.ActionTypes select DBActionTypeToActionType.Compile().Invoke(at));
我已经找了几天,我只能在Where子句中找到这样做的参考.看来,如果我能够使用函数调用来执行此操作,则应该可以使用查询语法.
I've been looking for a couple days now and I can only find references to doing this in the Where clause. It seems that if I'm able to use the function calls to do this, it should be possible using the query syntax.
使用查询语法很重要的原因是,某些被选择的对象是由许多子对象组成的,要想将所有转换与功能符号链接在一起,将变得更加困难.编写和维护.
The reason it is important to do use the query syntax is that some of the objects that are being selected are composed of many sub-objects and trying to chain them all of the conversions together with the function notation will be much harder to write and maintain.
推荐答案
那是不对的.查询表示法始终都是通过lambda表达式进行的.例如
That's not true. Query notation always goes via a lambda expression. For example
from x in y select z
最终为
y.Select(x => z)
这意味着,如果您已经有了要直接传递为Select
的参数的表达式树,则不能使用查询表达式,因为存在这种额外的间接级别.
That means if you've already got an expression tree that you want to pass directly as the argument to Select
, you can't use query expressions because there's this extra level of indirection.
现在可用的选项取决于您需要在哪里应用预定义的表达式.您始终可以在源代码中使用它,然后继续查询:
Now the options available depend on where you need to apply the predefined expression. You can always use it in the source, and then continue with the query:
var query = from foo in dc.ActionTypes.Select(DBActionTypeToActionType)
where foo.Stuff
select foo.Other;
或者在最后使用它很容易:
Or using it at the end is easy:
var query = (from bar in dc.ActionTypes
where bar.Stuff
select bar).Select(DBActionTypeToActionType);
这有帮助吗?
这篇关于在Linq select子句中重用表达式(查询格式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!