我正在试图弄清楚如何使用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
类的所有SmallThings
到Thing
属性。
答案 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)
)