Get the first and last item of an array of strings

后端 未结 5 1056
既然无缘
既然无缘 2021-02-05 06:35

If I have the following array of strings:

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

Is there a way to get the first and l

相关标签:
5条回答
  • 2021-02-05 07:08

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

    0 讨论(0)
  • 2021-02-05 07:10

    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);
    
    0 讨论(0)
  • 2021-02-05 07:22
    string[] stringArray = { "one", "two", "three", "four" };
    var last=stringArray.Last();
    var first=stringArray.First();
    
    0 讨论(0)
  • 2021-02-05 07:28

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

    0 讨论(0)
  • 2021-02-05 07:33

    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.

    0 讨论(0)
提交回复
热议问题