How do you retrieve the last element of an array in C#?
-
are you looking for how to retrieve the value stored in the last spot of the array, or the actual value of the index? – Nader Shirazie Jun 29 '09 at 05:59
-
2i mean the index value, that is, started from 0 to n – MAC Jun 29 '09 at 06:01
-
The title and content ask different questions. – Masea Jun 16 '20 at 04:53
12 Answers
LINQ provides Last():
csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();
5
This is handy when you don't want to make a variable unnecessarily.
string lastName = "Abraham Lincoln".Split().Last();
- 2,355
- 2
- 17
- 9
-
5
-
2Last is nice but it is very specific to get only the last item. Does C# have something like slice that can be used like `slice(-2)` to get the last 2 or `slice(0,-2)` to get items from the start except the last 2? Then a function like Last would not be needed as one could just do `slice(-1)` as I'm used to do in other languages. – HMR Dec 22 '16 at 04:48
-
3@HMR Yes, see this: https://www.infoq.com/articles/cs8-ranges-and-recursive-patterns – Matthew Steven Monkan May 07 '19 at 07:48
The array has a Length property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1.
string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
When declaring an array in C#, the number you give is the length of the array:
string[] items = new string[5]; // five items, index ranging from 0 to 4.
- 151,624
- 28
- 285
- 338
-
10This fails when the array has zero items, in which case `(items.Length - 1) == -1` – ftvs Dec 07 '12 at 02:57
-
8In C# 8 there is a new operator for indexing: `char[] arr = {'c', 'b', 'a'}; int a_last = arr[^1]; int b_second_last = arr[^2];` – Andrei Bozantan Sep 23 '20 at 15:54
int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5
- 6,555
- 3
- 49
- 67
-
Requires C# 8 and .Net Framework 4.8 or .Net Core 3. https://github.com/ashmind/SharpLab/issues/390 – jonyfries Aug 30 '21 at 12:48
New in C# 8.0 you can use the so-called "hat" (^) operator! This is useful for when you want to do something in one line!
var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
Console.WriteLine(lastword);
// World!
instead of the old way:
var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
Console.WriteLine(lastword);
// World!
It doesn't save much space, but it looks much clearer (maybe I only think this because I came from python?). This is also much better than calling a method like .Last() or .Reverse() Read more at MSDN
Edit: You can add this functionality to your class like so:
public class MyClass
{
public object this[Index indx]
{
get
{
// Do indexing here, this is just an example of the .IsFromEnd property
if (indx.IsFromEnd)
{
Console.WriteLine("Negative Index!")
}
else
{
Console.WriteLine("Positive Index!")
}
}
}
}
The Index.IsFromEnd will tell you if someone is using the 'hat' (^) operator
- 133
- 1
- 5
Use Array.GetUpperBound(0). Array.Length contains the number of items in the array, so reading Length -1 only works on the assumption that the array is zero based.
- 19,243
- 3
- 54
- 93
-
4
-
@mgttlinger, most of them are, but you can create non-zero-based arrays with http://msdn.microsoft.com/en-us/library/x836773a.aspx, or you may experience them when communicating with libraries written in other languages. – sisve Mar 21 '13 at 14:29
-
Awesome! Why isn't this up-voted (it's up to 3 with my vote at the time of this comment)? It's by far the most elegant, non-LINQ solution. – seebiscuit Feb 11 '14 at 15:00
-
UPDATE: The GetUpperBound(0) function will only return an `int`. It may not return what the user expects for other numerical arrays, and not all for non-numerical arrays. That's why this isn't up-voted past 3. – seebiscuit Feb 11 '14 at 16:01
To compute the index of the last item:
int index = array.Length - 1;
Will get you -1 if the array is empty - you should treat it as a special case.
To access the last index:
array[array.Length - 1] = ...
or
... = array[array.Length - 1]
will cause an exception if the array is actually empty (Length is 0).
- 163,328
- 92
- 501
- 942
The following will return NULL if the array is empty, else the last element.
var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
- 6,555
- 3
- 49
- 67
- 19,850
- 21
- 75
- 129
-
2This could also be written as `var item = (arr.Length == 0) ?? arr[arr.Length - 1]`. – Sep 25 '11 at 10:07
-
2@user215361 No, that is invalid C#. Your example will result in: `error CS0019: Operator '??' cannot be applied to operands of type 'bool' and 'int'` – Matthew Steven Monkan Mar 12 '19 at 01:56
Also, starting with .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index type to keep array's indexes from end:
var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];
You can use this index to get last array value in any length of array. For example:
var firstArray = new[] {0, 1, 1, 2, 2};
var secondArray = new[] {3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5};
var index = ^1;
var firstArrayLastValue = firstArray[index]; // 2
var secondArrayLastValue = secondArray[index]; // 5
For more information check documentation
- 6,555
- 3
- 49
- 67
- 3,116
- 1
- 15
- 26
-
1More on indices - A special value ^0 reduces to length of an array. So firstArray[^0] gives 'Index was outside the bounds of the array.' exception! – MBB Jun 02 '20 at 17:02
Is this worth mentioning?
var item = new Stack(arr).Pop();
- 6,555
- 3
- 49
- 67
- 6,736
- 10
- 49
- 101
-
2
-
2StilI not slow enough, what about converting into xml and evaluating on sql server? – Antonín Lejsek Aug 08 '20 at 20:49
Array starts from index 0 and ends at n-1.
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
int length = arr.Length - 1; // starts from 0 to n-1
Console.WriteLine(length); // this will give the last index.
Console.Read();
}
- 2,241
- 5
- 11
- 26
- 61
- 4
static void Main(string[] args)
{
int size = 6;
int[] arr = new int[6] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < size; i++)
{
Console.WriteLine("The last element is {0}", GetLastArrayIndex(arr));
Console.ReadLine();
}
}
//Get Last Index
static int GetLastArrayIndex(int[] arr)
{
try
{
int lastNum;
lastNum = arr.Length - 1;
return lastNum;
}
catch (Exception ex)
{
return 0;
}
}
- 1
- 1