我如何知道XML标记的索引

Luc*_*tos 1 c# linq

如何获取当前XML标记的索引?

例:

<User>
  <Contact>
    <Name>Lucas</Name>
  </Contact>
  <Contact>
    <Name>Andre</Name>
  </Contact>
    ...
</User>
Run Code Online (Sandbox Code Playgroud)

我正在尝试下面的代码

    foreach (var element2 in doc2.Root.Descendants())
    {
        String name = element.Name.LocalName;
        String value = element.Value;
    }
Run Code Online (Sandbox Code Playgroud)

我想知道我是在读第一个<Contact>标签,还是第二个,或第三个......

Aus*_*nen 5

使用适当的Select重载将在枚举集合时生成索引.

var userContacts = doc2.Root
                       .Descendants()
                       .Where(element => element.Name == "Contact")
                       .Select((c, i) => new {Contact = c, Index = i});

foreach(var indexedContact in userContacts)
{
     // indexedContact.Contact
     // indexedContact.Index                 
}
Run Code Online (Sandbox Code Playgroud)

注意:我添加了.Where,因为.Descendants会递归.