开发者

Linq-to-XML: Adding enumerations to objects

I'm trying to figure out how to add an enumeration to an object with Linq. For example:

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

This works well to create new Thing and add them to myList, but I can't figure out how to add the IEnumerable of String to my SmallThings list. For example, this doesn't work:

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

I just want to add all the <SmallThing>.@Name to SmallThings property of the Thing 开发者_如何学Cclass.


I'm not sure which values you wanted to extract from the <SmallThing>s but this seems to work.

' 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 _
    }))

The key was to convert the projection to a list since SmallThings expected a list (Select returns an IEnumerable(Of T))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜