6

Sometimes I need to get the last element in an Array if I split something. Although I didn't found any way to do it better than this way:

_Path.Split('\\')[_Path.Split('\\').Length - 1]

Is there maybe an easier way to do this than this one? In this case it's pretty nice to understand, but if it gets longer, it isn't anymore.

Daniel Frühauf
  • 311
  • 1
  • 2
  • 12

3 Answers3

8

Use the Last or LastOrDefault extension methods:

_Path.Split('\\').Last()
  • Last will throw an exception if there are no elements
  • LastOrDefault will return the default value - default(T) - which is null for reference types

You need to add:

using System.Linq;
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
3

Use LINQ's method Last():

_Path.Split('\\').Last();

Don't forget using System.Linq; is required.

Jens R.
  • 191
  • 5
1

Is there maybe an easier way to do this than this one?

Yes, using Enumerable.Last:

var last = _Path.Split('\\').Last();

If you're not sure Path.Split will yield any items, use Enumerable.LastOrDefault and check against null.

var last = _Path.Split('\\').LastOrDefault();
if (last != null)
{
    // Do stuff.
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321