LINQ到XML转换-dictionary(Linq to XML -Dictionary conv

2019-08-21 11:06发布

如何存储以下内容解释其中int是使用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**; 

如何把我的选择到Dictionary<int,String> ? (密钥应从1开始;在LINQ indicies从零开始)。

Answer 1:

怎么样:

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


文章来源: Linq to XML -Dictionary conversion