Linq to XML -Dictionary conversion

2019-02-22 08:52发布

问题:

How to store the nodes of the following into Dictionary where int is an autogenerated Key and string (value of the node) using LINQ ?

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**; 

How to turn my selection into Dictionary<int,String> ? (Key should start from 1;In Linq indicies start from Zero).

回答1:

How about:

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