代码之家  ›  专栏  ›  技术社区  ›  AndrewC

从XElement获取2个属性以创建字典LINQ

  •  1
  • AndrewC  · 技术社区  · 14 年前

    我尝试将一个属性用作键,另一个属性用作值。如果我使用(示例中xDoc是XDocument对象):

    Dictionary<string, XElement> test = xDoc.Descendants()
        .Where<XElement>(t => t.Name == "someelement")
        .ToDictionary<XElement, string>(t => t.Attribute("myattr").Value.ToString());
    

    我想做的是,选择第二个属性作为每个dictionary项的value属性,但似乎无法解决这个问题。

    是否可以在1 Linq语句中完成所有这些操作?好奇吸引了我!

    2 回复  |  直到 14 年前
        1
  •  4
  •   driis    14 年前

    是的,可以传入另一个表达式以选择所需的值:

    Dictionary<string,string> test = xDoc.Descendants()
        .Where(t => t.Name == "someelement")
        .ToDictionary(
            t => t.Attribute("myattr").Value.ToString(), 
            t => t.Attribute("otherAttribute").Value.ToString());
    
        2
  •  1
  •   48klocs    14 年前

    .ToDictionary()调用中的强制转换将翻转对象定义中的参数。

    你所要做的就是删除它并添加一个identity select,它应该可以工作。

    Dictionary<string, XElement> test = xDoc.Descendants()
                .Where<XElement>(t => t.Name == "someelement")
                .ToDictionary(t => t.Attribute("myattr").Value.ToString(), t => t);