2009-10-20 16 views
5

Cómo almacenar los nodos de lo siguiente en Dictionary donde int es una Clave autogenerada y una cadena (valor del nodo) usando LINQ?Linq a XML -Dictionary conversion

Elements:

XElement instructors = 
     XElement.Parse(
          @"<instructors> 
           <instructor>Daniel</instructor> 
           <instructor>Joel</instructor> 
           <instructor>Eric</instructor> 
           <instructor>Scott</instructor> 
           <instructor>Joehan</instructor> 
         </instructors>" 
     ); 

partially attempted code is given below :

var qry = from instr in instructors.Elements("instructor") 
where((p,index)=> **incomplete**).select..**incomplete**; 

Cómo activar mi selección en Dictionary<int,String>? (La clave debe comenzar desde 1; en Linq las indicaciones comienzan desde cero).

Respuesta

8

¿Qué tal:

var dictionary = instructors.Elements("instructor") 
          .Select((element, index) => new { element, index }) 
          .ToDictionary(x => x.index + 1, 
              x => x.element.Value); 
+1

Sí, está funcionando muy bien; Gracias –

+0

¿Ha dejado artículos especiales sobre LINQ? –

+0

No realmente, pero blogueo cada cierto tiempo. –