【问题标题】:LINQ to XML - how do I obtain indexLINQ to XML - 如何获取索引
【发布时间】:2011-04-14 16:42:43
【问题描述】:

我有一个 Car 对象数组,并使用以下代码从这些对象创建一个 XML 文档。我设置了一个计数器变量i,以便能够索引文档中的 Car 元素。是否有不同的方式获取当前处理的元素的索引?

        int i = 0;
        XDocument doc =
            new XDocument(
                new XElement(
                    "Inventory",
                    from car in cars
                    select
                        new XElement("Car",
                            new XAttribute("ID", ++i), //<<== index here
                            new XElement("Color", car.Color),
                            new XElement("Make", car.Make),
                            new XElement("PetName", car.PetName)
                        )
                )
            );

我采用的方法效果很好,我只是想知道是否有一个神奇的词或扩展方法可以在不增加计数器变量的情况下产生索引?

【问题讨论】:

    标签: c# linq xml-serialization linq-to-xml indexing


    【解决方案1】:

    是的 - 不要使用查询表达式;使用overload of Select which provides an index。这将替换您的查询表达式:

    cars.Select((car, index) =>
        new XElement("Car",
            new XAttribute("ID", index),
            new XElement("Color", car.Color),
            new XElement("Make", car.Make),
            new XElement("PetName", car.PetName)
        ))
    

    查询表达式不支持各种重载 - 绝对值得熟悉“点表示法”(或任何您想调用的名称)和查询表达式。

    【讨论】:

      【解决方案2】:

      有一个overload of Select which takes an index,因此您可以将查询表达式更改为:

      cars.Select((c, i) => new XElement("Car", new XAttribute("ID", i) ...))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-22
        • 1970-01-01
        • 2013-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多