If I have the following array of strings:
string[] stringArray = {\"one\", \"two\", \"three\", \"four\"};
Is there a way to get the first and l
There are stringArray.First()
and stringArray.Last()
as extension methods in the System.Linq namespace.
First
Console.WriteLine(stringArray.First());
Console.WriteLine(stringArray.ElementAt(0));
Console.WriteLine(stringArray[0]);
var stringEnum = stringArray.GetEnumerator();
if (stringEnum.MoveNext())
Console.WriteLine(stringEnum.Current);
Last
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);
string[] stringArray = { "one", "two", "three", "four" };
var last=stringArray.Last();
var first=stringArray.First();
You can use stringArray.GetUpperBound(0) to get the index of the last item.
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.