Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top