Mehmet Yüce
Mehmet Yüce

Reputation: 59

picking one of the value of foreach values

This code returns 7 values. I just want to retrieve the 7th value.

Could you give me some advice?

var a_nodes = root.Descendants("type");
foreach (var a_node in a_nodes)
{                          
     Console.WriteLine("{0}", a_node.GetAttributeValue("value", ""));
}

Upvotes: 0

Views: 63

Answers (3)

jmcilhinney
jmcilhinney

Reputation: 54417

If a_nodes implements IEnumerable<T> then you can call the Last extension method on it to get the last item in the list. If it implements IEnumerable but not IEnumerable<T> then you can call Cast before Last. If there may not be any items in the list then you should call LastOrDefault instead.

If you don't want to use LINQ or can't and a_nodes implements IList then you can get the Count and then the item at the index 1 less than that.

Upvotes: 1

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13765

Seventh node

var lastnode = root.Descendants("type").Last();

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

root.Descendants("type").Last()

Or:

root.Descendants("type").Skip(6).First();

Upvotes: 3

Related Questions