简体   繁体   中英

Accessing Linq to XML query results with [] in C#

In this post , the Linq to XML query result are accessed with iterator as follows.

foreach (var elem in elems) {
    var res = elem.Elements("ClassKeyName");

    foreach (var e in res) {
        Console.WriteLine(e.Value);
    }
}

Can I access the result with []? For example, I want to use as follows,

foreach (var elem in elems) {
    var res = elem.Elements("ClassKeyName");
    Console.WriteLine(res[0].Value);
}

However, I got this error message

xmlparse.cs(18,34): error CS0021: 
Cannot apply indexing with [] to an expression of type
`System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>'

You'd just have to convert the results to an indexable type, such as a list:

foreach (var elem in elems) {
    List<XElement> res = elem.Elements("ClassKeyName").ToList();
    Console.WriteLine(res[0].Value);
}

(You can still use var if you want - I've just given it an explicit type to make it clearer in this case.)

If you only need the first, you can res.First().Value . If you need the n-th element res.Skip(n - 1).Value (so the first element is res.Skip(0).Value , the second res.Skip(1).Value ...).

The big question is WHY? What do you want to do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM