Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the last three elements from the string array in c# [duplicate]

Tags:

arrays

string

c#

I have a string array in c#.Now as per my requirement i have to get the last ,second last and one element before second last elements in string but i am not getting how to get it. Here is my string array.With Last() i am able to get the last element but second last and before second last i am not getting to find out.

 string[] arrstr = str.Split(' ');

With .Last() i am able to get the last element but rest of the elements i am not able to get. Please help me..

like image 781
user3924730 Avatar asked Oct 15 '25 14:10

user3924730


2 Answers

Use:

  string[] arrstr = str.Reverse().Take(3).Reverse().ToArray();

In more recent versions of c# you can now use:

  string[] arrstr = str.TakeLast(3).ToArray();
like image 190
thumbmunkeys Avatar answered Oct 17 '25 05:10

thumbmunkeys


It actually gets the number of elements and skip the remaining element from the total count and take the specified amount you can replace the 3 with N and use as method

string[] res = arrstr.Skip(Math.Max(0, arrstr.Count() - 3)).Take(3).ToArray();
like image 40
Sajeetharan Avatar answered Oct 17 '25 06:10

Sajeetharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!