【问题标题】:Using Generics in Linq Query?在 Linq 查询中使用泛型?
【发布时间】:2009-07-28 12:59:47
【问题描述】:

我正在尝试编写一个基于对象列表和对象属性生成 Xelement 的通用函数

目前我已将此代码复制并粘贴到多个位置

 InputElementsArray = New XElement(New XElement("ArrayInputs", _
                   New XElement("InputName", "TestFailedRefDesList"), _
                   New XElement("DataType", "StringArray"), _
                   New XElement("ValueList", From d In _PassFailItem.FailureDetails Select New XElement("InputValue", d.RefDes))))
    InputElements.Add(InputElementsArray)

上面的代码对我来说很好用,但我更愿意创建一个函数,在给定对象和属性的情况下执行相同的任务

Private Shared Function CreateBaseArrayInputs(Of T)(ByVal ListOfItems As List(Of T)) As XElement
    Dim InputElementsArray As XElement = _
         New XElement("ArrayInputs", _
                  New XElement("InputName", "TestFailureCodeList"), _
                  New XElement("DataType", "StringArray"), _
                  New XElement("ValueList", From d In ListOfItems Select New XElement("InputValue", d)))
    Return InputElementsArray
End Function

我不确定如何将 d 的属性设置为使用。有什么想法吗?

【问题讨论】:

    标签: vb.net linq linq-to-xml


    【解决方案1】:

    除了使用 XML 文字之外,我还会像这样将你的值选择器传递给你的函数:

    Private Shared Function CreateBaseArrayInputs(Of T, TValue)( _
            ByVal ListOfItems As List(Of T), _
            ByVal selector As Func(Of T, TValue)) As XElement
    
        Return <ArrayInputs>
                   <InputName>TestFailureCodeList</InputName>
                   <DataType>StringArray</DataType>
                   <ValueList>
                       <%= From d In ListOfItems _
                           Select <InputValue><%= selector(d) %></InputValue> %>
                   </ValueList>
               </ArrayInputs>
    End Function
    

    你会这样称呼:

     Dim TestArray As XElement = CreateBaseArrayInputs(_PassFailItem.FailureDetails, Function(d) d.FailureCodes)
    

    【讨论】:

    • 这与我将使用的代码非常相似,它只是简化了传递数据的过程。谢谢
    【解决方案2】:

    我认为您不能使用泛型指定属性。我 C# 你 cat 使用 where keyword 对 T 进行了限制,但似乎这在 VB.NET 中不可用。

    该限制将允许您指定您的 T 元素必须实现一个接口,因此您会知道该接口的属性是可用的。

    【讨论】:

    • 谢谢。忘了VB和C#不共享关键字。
    【解决方案3】:

    我找到了解决问题的方法。它不像我希望的那样优雅,但它仍然有效

    这里是调用代码

     Dim TestArray As XElement = CreateBaseArrayInputs((From d In _PassFailItem.FailureDetails Select New XElement("InputValue", d.FailureCodes)))
    

    这里是调用函​​数

    Private Shared Function CreateBaseArrayInputs(ByVal ListOfItems As IEnumerable(Of XElement)) As XElement
        Dim InputElementsArray As XElement = _
             New XElement("ArrayInputs", _
                      New XElement("InputName", "TestFailureCodeList"), _
                      New XElement("DataType", "StringArray"), _
                      New XElement("ValueList", ListOfItems))
        Return InputElementsArray
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多