Try this:
TableRow firstRow = theTable.Elements<TableRow>().Reverse().Skip(1).First();
Note, that this expression can throw an exception if no suitable row is available (also Last
and First
).
質問
If getting the first/last row is as following:
TableRow lastRow = theTable.Elements<TableRow>().Last();
TableRow firstRow = theTable.Elements<TableRow>().First();
How to select the second last row?
解決
Try this:
TableRow firstRow = theTable.Elements<TableRow>().Reverse().Skip(1).First();
Note, that this expression can throw an exception if no suitable row is available (also Last
and First
).
他のヒント
If you know the count, you can find k
-th element from the back by subtraction, like this:
var k = 2; // Second element from the back
var total = theTable.Elements<TableRow>().Count();
if (total < k) throw ... // Not enough elements
var kThFromBack = theTable.Elements<TableRow>().Skip(total-k).First();
Simple one
TableRow lastButOneRow= theTable.Rows[theTable.Rows.Count-2]
Made a little extension method:
public static T NthLast<T>(this IEnumerable<T> source, int count)
{
if (count < 0)
throw new ArgumentException("count must be >= 0");
int i = 0;
var queue = new Queue<T>(count);
using (var e = source.GetEnumerator())
{
while (e.MoveNext())
{
queue.Enqueue(e.Current);
if (i++ > count)
queue.Dequeue();
}
if (count >= i)
throw new ArgumentException("count was greater than length");
}
return queue.Dequeue();
}
To get second last element:
var secondLast = theTable.Elements<TableRow>().NthLast(1)