【问题标题】:Dynamic Linq Library to generate particular type object for selected properties为选定属性生成特定类型对象的动态 Linq 库
【发布时间】:2013-05-04 21:02:35
【问题描述】:

我正在为我的应用程序使用动态 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

需要您对此的意见..

【问题讨论】:

    标签: linq


    【解决方案1】:

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

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

    【讨论】:

    • 嗨,Haris,动态 Linq 库不接受 .Select。我们不能在选择子句旁边传递类型。我应该在动态 Linq 库中根据上面的代码更改代码
    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2019-01-16
    • 2018-06-28
    • 2019-10-14
    • 1970-01-01
    • 2019-01-02
    • 2019-04-05
    相关资源
    最近更新 更多