2014-02-05 41 views
0

该代码返回7个值。我只想检索第7个值。选择一个值的foreach值

你能给我一些建议吗?

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

'root.Descendants(“type”)。Last()'? –

回答

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

或者:

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

即时得到此错误:在System.Core.dll中发生类型'System.InvalidOperationException'的未处理的异常 –

+0

我相信它与此代码无关。 –

1

第七节点

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

如果a_nodes实现IEnumerable<T>那么你可以调用它的最后一个扩展方法来获取列表中的最后一个项目。如果它实现IEnumerable而不是IEnumerable<T>那么你可以调用Cast before Last。如果列表中没有任何项目,则应调用LastOrDefault。

如果你不想使用LINQ或不能和a_nodes实现IList,那么你可以得到计数,然后在索引1的项目比这少。