Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the last index of an array

Tags:

arrays

c#

How do you retrieve the last element of an array in C#?

like image 493
MAC Avatar asked Jun 29 '09 05:06

MAC


People also ask

What is the last index of an array in C?

Arrays in C are indexed starting at 0, as opposed to starting at 1. The first element of the array above is point[0]. The index to the last value in the array is the array size minus one.

What is the last index of an array Java?

The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter.

How do I find the last 5 elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array. Copied!


2 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(); 
like image 143
dribnet Avatar answered Sep 29 '22 06:09

dribnet


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. 
like image 23
Fredrik Mörk Avatar answered Sep 29 '22 05:09

Fredrik Mörk