Depending on your C# version (8.0+) you may also have access to an unary expression that counts the index in reverse from the current collection.
E.g. just like indexing from the front [0] to get 1st entry, you can get the the last entry by counting from the back [^1].
This is to be read like "length-1" of the current collection.
private readonly string[] _entries = new[]
{
"Hello",
"How's life?",
"Likewise",
"Bye"
};
public string GetLastEntry()
{
return _entries[^1]; // Returns "Bye" and is the same as "_entries[_entries.Length-1]"
}
So for your particular example, you could just use string.Join() for the string-based use case, but let's try the reverse index. With those, we could output the last n entries like here:
private readonly string[] _entries = { "S1", "S2", "S3", "S4" };
public string GetTailingEntries(int depth)
{
if (depth < 0 || depth > _entries.Length)
{
// Catch this however you require
throw new IndexOutOfRangeException();
}
string output = _entries[^depth--];
while (depth > 0)
{
output += $".{_entries[^depth--]}";
}
return output;
}
Essentially we take any depth, let's take '2' like in your question. It would initialize the output with the furthest entry from the end ([^2]) which is "S3" and decrement the depth, putting the next entry at [^1]. In the loop we append the values to the output until we reached our desired depth.
GetTailingEntries(2) // "S3" -> "S3.S4"
GetTailingEntries(4) // "S1" -> "S1.S2" -> "S1.S2.S3" -> "S1.S2.S3.S4"