how to take all array elements except last element in C#

后端 未结 6 821
滥情空心
滥情空心 2020-12-14 14:50

I have a string array like this.

string[] queries with data more than one string.

I want to skip the last string from the element and take the r

6条回答
  •  失恋的感觉
    2020-12-14 15:11

    For anyone finding this now...

    With the upcoming support for ranges and indices C# 8 and .NET Core 3.0 you can simply write

    var remStrings = queries[..^1]
    

    This is short for

    var remStrings = queries[0..^1]
    

    This works by converting the 0 and 1 to indices (System.Index), with the ^ being the marker (actually an operator) to index from the end of a sequence. From these indices a range (System.Range) is then generates which can then be used to access the array. (See https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges)

    Currently this only works in the preview version of .NET Core 3.0

提交回复
热议问题