2

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..

user3924730
  • 163
  • 1
  • 3
  • 14

6 Answers6

12

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();
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
  • 1
    There is now a .TakeLast(3) method available in LINQ: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.takelast?view=net-6.0 – Ovenkoek Jun 02 '22 at 08:37
2

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();
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
2
var threeLastElments = arrstr.Reverse().Take(3).Reverse().ToArray();
IL_Agent
  • 707
  • 3
  • 16
1

Get a substring:string arrstr = str.Substring(str.Length - 4, 3);

More on C# strings

JKS
  • 339
  • 1
  • 12
0

Why don't you calculate the length using obj.length; and then use arr[i] inside the loop and start the loop from last value.

Smoking monkey
  • 323
  • 1
  • 6
  • 22
  • `int len = arrstr.length; for(int i= len ; i>= len-2; i--) { int j = 0; String[] newArr = new String[3]; newArr[j] = arrstr[i]; j++; }` – Smoking monkey Aug 19 '14 at 12:59
0

To offer another solution, one which will be much more performant than LINQ queries ...

 public static string[] getLast3(string[] src)
    {
        if (src.Length <= 3)
            return src;
        var res = new string[3];
        Array.Copy(src, src.Length - 3, res, 0, 3);
        return res;
    }
Terje
  • 1,753
  • 10
  • 13