【问题标题】:select two attributes in a node using LINQ使用 LINQ 在节点中选择两个属性
【发布时间】:2009-02-27 03:04:15
【问题描述】:

我有以下节点:

<NodeA desc="Cheap Item 1" category="Cooking" />

我使用以下方法选择了“类别”属性:

.Where(attr => attr.Name == "category")
.Select(attr => attr.Value);

我现在如何选择“desc”和“category”

【问题讨论】:

    标签: c# .net linq linq-to-xml


    【解决方案1】:

    编辑我想我实际上误解了你原来的问题。下面的代码应该在节点列表中找到合适的节点并选择它的desccategory 属性。

    var contents = nodes.Where( n => n.Name == "NodeA")
                        .Select( node => new { desc = node.Attribute("desc")
                                                          .Value,
                                              category = node.Attribute("category")
                                                              .Value
                                             }
                         );
    
    var desc = contents.desc;
    var category = contents.category;
    

    【讨论】:

    • 谢谢,但这并没有在我的最后编译..它说'字符串'不包含'属性'的定义和最佳扩展方法重载'......
    • 是的。我想我误解了你从哪里开始。我想我已经根据更好的理解对其进行了更正。
    • 基本上,跳过所有属性的迭代,并在按名称选择节点后从节点本身中获取命名属性。如果您已经从其他查询中获得了节点,则可以使用 var desc = node.Attribute("desc").Value; var category = node.Attribute("category").Value.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多