Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

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 remaining. I have come up with

var remStrings = queries.Reverse().Skip(1).Take(queries.Length - 1); 

Is there a better alternative to this?

like image 942
dotcoder Avatar asked Jul 16 '10 12:07

dotcoder


People also ask

How do you skip the last element of an array?

To remove the last n elements from an array, use arr. splice(-n) (note the "p" in "splice"). The return value will be a new array containing the removed elements.

What is the last element of array in C?

The last element of an array is at position size - 1.


2 Answers

var remStrings = queries.Take(queries.Length - 1); 

No need to Reverse and Skip. Just take one less element than there are in the array.

If you really wanted the elements in the reverse order, you could tack on a .Reverse() to the end.

like image 111
Justin Niessner Avatar answered Oct 03 '22 07:10

Justin Niessner


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

like image 32
user1781290 Avatar answered Oct 03 '22 06:10

user1781290