Linq-to-XML:向对象添加枚举

时间:2010-10-02 04:51:41

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

我正在试图弄清楚如何使用Linq向对象添加枚举。例如:

Dim thingBlock = <Things>
                      <Thing Name="Ish">
                          <SmallThing>Jibber</SmallThing>
                          <SmallThing>Jabber</SmallThing>
                      </Thing>
                      <Thing Name="Ugly Guy">
                         <SmallThing Name="Carl"></SmallThing>
                         <SmallThing Marks="Marks"></SmallThing>
                      </Thing>
                  </Things>
Dim myList As New List(Of Thing)
myList.AddRange(thingBlock.<Thing>.Select(Function(th) New Thing With {.Name = th.@Name}))

Public Class Thing
    Public Property Name As String
    Public Property SmallThings As New List(Of String)
End Class

这适用于创建新的Thing并将它们添加到myList,但我无法弄清楚如何将IE的IEnumerable添加到我的SmallThings列表中。例如,此工作:

myList.AddRange(thingBlock.<Thing>.Select(Function(th) New Thing With {.Name = th.@Name, th.Select(Function(st) .SmallThings.Add(st.Elements.@Name.ToString)}))

我只想添加<SmallThing>.@Name类的所有SmallThingsThing属性。

1 个答案:

答案 0 :(得分:3)

我不确定您要从<SmallThing>中提取哪些值,但这似乎有效。

' adds "Jibber" and "Jabber" '
myList.AddRange(thingBlock.<Thing>.Select(Function(th) New Thing With         _
    {                                                                         _
        .Name = th.@Name,                                                     _
        .SmallThings = th...<SmallThing>.Select(Function(st) st.Value).ToList _
    }))

' adds "Carl" '
myList.AddRange(thingBlock.<Thing>.Select(Function(th) New Thing With         _
    {                                                                         _
        .Name = th.@Name,                                                     _
        .SmallThings = th...<SmallThing>.Select(Function(st) st.@Name).ToList _
    }))

关键是将投影转换为列表,因为SmallThings预期列表(Select返回IEnumerable(Of T)