[lang-ref] ( example_trim_trailing_empty_elements ) ( csharp )

[Fact]
public void TestExampleTrimTrailingEmptyElements()
{
    // use FindLastIndex
    {
        List<string> items = new() { "A", "", "B", "", "", "C", "", "", "" };
        List<string> expected = new() { "A", "", "B", "", "", "C" };

        int lastNonEmptyIndex = items.FindLastIndex(x => x != "");
        List<string> actual = items.Take(lastNonEmptyIndex + 1).ToList();


        Assert.Equal(expected, actual);
    }

    {
        List<string> items = new() { "A", "", "B", "", "", "C" }; // already trimmed
        List<string> expected = new() { "A", "", "B", "", "", "C" };

        int lastNonEmptyIndex = items.FindLastIndex(x => x != "");
        List<string> actual = items.Take(lastNonEmptyIndex + 1).ToList();


        Assert.Equal(expected, actual);
    }

    {
        List<string> items = new() {}; // empty
        List<string> expected = new() {};

        int lastNonEmptyIndex = items.FindLastIndex(x => x != "");
        List<string> actual = items.Take(lastNonEmptyIndex + 1).ToList(); // When the list is empty, FindLastIndex returns -1, so Take(0) is used.

        Assert.Equal(-1, lastNonEmptyIndex);
        Assert.Equal(expected, actual);

        // Note: I finally understand why APIs return -1 when no match is found.
    }
}
[Fact]
public void TestExampleTrimTrailingEmptyElementsAlternative()
{
    // not functional
    List<string> items = new() { "A", "", "B", "", "", "C", "", "", "" };
    List<string> expected = new() { "A", "", "B", "", "", "C" };

    while (items.Count > 0 && items.Last() == "")
    {
        items.RemoveAt(items.Count - 1);
    }

    Assert.Equal(expected, items);
}