【问题标题】:Linq to XML -Dictionary conversionLinq to XML - 字典转换
【发布时间】:2009-10-20 16:47:51
【问题描述】:

如何将以下节点存储到字典中,其中 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&lt;int,String&gt;? (键应从 1 开始;在 Linq 中,索引从零开始)。

【问题讨论】:

    标签: c# linq-to-xml


    【解决方案1】:

    怎么样:

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

    【讨论】:

    • 你写过关于LINQ的特别文章吗?
    • 不是真的——不过我经常在博客上讨论它。
    猜你喜欢
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多