2010-10-02 65 views
1

我想弄清楚如何將枚舉添加到Linq對象。例如:Linq到XML:將枚舉添加到對象

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 

這能很好地創造新的Thing並將它們添加到myList,但我無法弄清楚如何爲String的IEnumerable的添加到我的SmallThings名單。例如,這工作:

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

我只是想添加的所有Thing類的<SmallThing>[email protected]SmallThings財產。

回答

3

我不確定你想要從<SmallThing>中提取哪些值,但這似乎有效。

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

的關鍵是投影轉換到一個列表,因爲SmallThings預期的列表(Select返回IEnumerable(Of T)

+0

完美,這是'.ToList'奏效。好東西! – 2010-10-02 06:30:46