c# - Linq to XML - 字典转换

标签 c# linq-to-xml

如何使用 LINQ 将以下节点存储到字典中,其中 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 to XML - 字典转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1593235/

相关文章:

c# - 将 JSON 字符串反序列化为 Dictionary<string,object>

c# - 字段相等需要什么条件?

c# - 如何在 PropertyGrid TypeConversion 中获取旧值?

c# - XDocument 保存删除节点前缀

.net - 在 XElement 中获取空格

c# - XDocument中当前节点的路径

c# - 选择一些特定的 xml 元素到匿名对象列表

c# - 重构代码以避免类型转换

c# - 如果找到字符串,则执行 switch 语句

c# - LINQ to XML 用作简单的数据抽象层?