Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first and last item of an array of strings

Tags:

arrays

c#

If I have the following array of strings:

string[] stringArray = {"one", "two", "three", "four"};

Is there a way to get the first and last item ("one", "four") in C# from the array, besides using array indexing (stringArray[0], stringArray[3]), something like stringArray.First and stringArray.Last ?

like image 445
Adrian Avatar asked Sep 12 '11 11:09

Adrian


People also ask

How do I find the first and last elements of an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.

How do you get the first string of an array?

To access the first element of an array, we can use the subscript syntax [] by passing the index 0 which is the index of the first element.

How do you access the last element of an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How do you find the first object of an array?

To get first element from array, use var first = array[0]; To get Name from it, use first.Name .


5 Answers

Use LINQ First() and Last() methods.

Moreover, both methods have useful overload which allows specifying boolean condition for elements to be considered as first or last.

like image 53
sll Avatar answered Sep 29 '22 12:09

sll


string[] stringArray = { "one", "two", "three", "four" };
var last=stringArray.Last();
var first=stringArray.First();
like image 35
Massimiliano Peluso Avatar answered Sep 25 '22 12:09

Massimiliano Peluso


There are stringArray.First() and stringArray.Last() as extension methods in the System.Linq namespace.

like image 23
Jens Avatar answered Sep 27 '22 12:09

Jens


Different ways to get the first index from the array:

Console.WriteLine(stringArray.First());
Console.WriteLine(stringArray.ElementAt(0));
Console.WriteLine(stringArray[0]);
var stringEnum = stringArray.GetEnumerator();
if (stringEnum.MoveNext())
    Console.WriteLine(stringEnum.Current);

Different ways to get the last index from the array:

Console.WriteLine(stringArray.Last());
if (stringArray.Any())
    Console.WriteLine(stringArray.ElementAt(stringArray.Count()-1));
Console.WriteLine(stringArray[stringArray.Length -1]);
var stringEnum = stringArray.GetEnumerator();
string lastValue = null;
while (stringEnum.MoveNext())
    lastValue = (string)stringEnum.Current;
Console.WriteLine(lastValue);
like image 26
Muhammad Hasan Khan Avatar answered Sep 28 '22 12:09

Muhammad Hasan Khan


You can use stringArray.GetUpperBound(0) to get the index of the last item.

like image 30
Tys Avatar answered Sep 28 '22 12:09

Tys