0

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>'
Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

1

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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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?

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Thanks for letting me know about First(), actually, this was what I wanted to get. However, ToList() works fine, and it's good to know about it either. – prosseek Feb 16 '11 at 17:17