Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created July 9, 2024 17:34
Show Gist options
  • Select an option

  • Save admir-live/c8d38e1630510c314348288635be160e to your computer and use it in GitHub Desktop.

Select an option

Save admir-live/c8d38e1630510c314348288635be160e to your computer and use it in GitHub Desktop.
Accessing the last element
public class Program
{
public static void Main()
{
List<string> personList = new List<string> { "Alice", "Bob", "Charlie", "David", "Eve" };
// Accessing the last element
string lastPerson = personList[^1];
Console.WriteLine($"Last person: {lastPerson}"); // Output: Eve
// Accessing the second last element
int i = 2;
string secondLastPerson = personList[^i];
Console.WriteLine($"Second last person: {secondLastPerson}"); // Output: David
// Accessing the third last element
i = 3;
string thirdLastPerson = personList[^i];
Console.WriteLine($"Third last person: {thirdLastPerson}"); // Output: Charlie
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment