LINQ to XML - 如何获取索引
我有一个 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)
)
)
);
我采取的方法效果很好,我只是想知道是否有一个神奇的词或扩展方法可以在不增加计数器变量的情况下产生索引?
I have an array of Car objects and using the following piece of code I create an XML Document from these objects. I have set up a counter variable i
to be able to index the Car elements in the document. Is there a different way of obtaining the index of the currently processed element?
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)
)
)
);
The approach I have taken works fine, I am just wondering whether there's a magic word or extension method that will yield the index without my incrementing a counter variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的 - 不要使用查询表达式;使用重载提供索引的
Select
。这取代了您的查询表达式:查询表达式不支持各种重载 - 熟悉“点表示法”(或任何您想称呼它的内容)和查询表达式绝对值得。
Yup - don't use a query expression; use the overload of
Select
which provides an index. This replaces your query expression:There are various overloads which aren't supported in query expressions - it's definitely worth being familiar with both "dot notation" (or whatever you want to call it) and query expressions.
Select 的重载需要一个索引,因此您可以更改您的查询表达式为:
There is an overload of Select which takes an index so you can change your query expression to this: