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 ?
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.
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.
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.
To get first element from array, use var first = array[0]; To get Name from it, use first.Name .
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.
string[] stringArray = { "one", "two", "three", "four" };
var last=stringArray.Last();
var first=stringArray.First();
There are stringArray.First()
and stringArray.Last()
as extension methods in the System.Linq namespace.
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);
You can use stringArray.GetUpperBound(0)
to get the index of the last item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With