2010-10-02 4 views
1

J'essaie de comprendre comment ajouter une énumération à un objet avec Linq. Par exemple:Linq-to-XML: Ajout d'énumérations aux objets

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 = [email protected]})) 

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

Cela fonctionne bien pour créer de nouveaux Thing et les ajouter à myList, mais je ne peux pas comprendre comment ajouter le IEnumerable de cordes à ma liste SmallThings. Par exemple, ce ne le fait pas travail:

myList.AddRange(thingBlock.<Thing>.Select(Function(th) New Thing With {.Name = [email protected], th.Select(Function(st) .SmallThings.Add([email protected])})) 

Je veux juste ajouter tous les <SmallThing>[email protected]-SmallThings propriété de la classe Thing.

Répondre

3

Je ne suis pas sûr de savoir quelles valeurs vous voulez extraire du <SmallThing> s mais cela semble fonctionner.

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

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

La clé était de convertir la projection à la liste depuis SmallThings prévu une liste (Select retourne un IEnumerable(Of T))

+0

parfait, il était '.ToList' qui a fonctionné. Des trucs géniaux! –