如何使用LINQ将以下节点存储到Dictionary中,其中int是自动生成的键和字符串(节点的值)?

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

如何将我的选择转换为Dictionary<int,String>? ( key 应从1开始;在Linq中,索引应从零开始)。

最佳答案

怎么样:

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

关于c# - Linq到XML-字典转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1593235/

10-10 22:14