动态Linq库为选定的属性生成特定类型对象

时间:2013-05-04 21:02:36

标签: linq

我在我的应用程序中使用动态LINQ库,在动态LINQ库的示例中, 我们可以将逗号分隔列名称或属性名称的字符串传递给LINQ的select子句 如下 .Select(“new(AccountingDocumentNbr,DocumentFiscalYearNbr)”);

我们可以传递一些对象来实例化并将属性值填充到对象中,如下所示

.Select(“new AccountingObject(AccountingDocumentNbr,DocumentFiscalYearNbr)”);

AccountingObject将具有AccountingDocumentNbr,DocumentFiscalYearNbr。是否可以使用Dynamic LINQ Library执行此操作。 http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

需要你的输入..

1 个答案:

答案 0 :(得分:2)

嗯,理论上你的代码应该是这样的:

Function ParseNew() As Expression
    NextToken()
    ValidateToken(TokenId.OpenParen, Res.OpenParenExpected)
    NextToken()
    Dim properties As New List(Of DynamicProperty)()
    Dim expressions As New List(Of Expression)()
    Do
        Dim exprPos = tokenVal.pos
        Dim expr = ParseExpression()
        Dim propName As String
        If TokenIdentifierIs("as") Then
            NextToken()
            propName = GetIdentifier()
            NextToken()
        Else
            Dim [me] As MemberExpression = TryCast(expr, MemberExpression)
            If [me] Is Nothing Then Throw ParseError(exprPos, Res.MissingAsClause)
            propName = [me].Member.Name
        End If
        expressions.Add(expr)
        properties.Add(New DynamicProperty(propName, expr.Type))
        If tokenVal.id <> TokenId.Comma Then Exit Do
        NextToken()
    Loop
    ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected)
    NextToken()
    Dim type As Type = If(newResultType, DynamicExpression.CreateClass(properties))
    Dim bindings(properties.Count - 1) As MemberBinding
    For i As Integer = 0 To bindings.Length - 1
        bindings(i) = Expression.Bind(type.GetProperty(properties(i).Name), expressions(i))
    Next
    Return Expression.MemberInit(Expression.[New](type), bindings)
End Function

但是你如何调用Select方法?它应该看起来或多或少像这样:

 .Select<ObjectHolder>("new (Activity as Activity, ActivityName as ActivityName)")
相关问题