开发者

Reusing Expression in Linq select clause (query format)

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);

But I'd like to use it like this:

var linq = (from at in dc.SQLRepositoryDC.ActionTypes select DBActionTypeToActionType.Compile().Invoke(at));

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.


It seems that if I'm able to use the function calls to do this, it should be possible using the query syntax.

That's not true. Query notation always goes via a lambda expression. For example

from x in y select z

ends up as

y.Select(x => z)

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);

Does that help at all?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜