2

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
  • 271
  • 2
  • 12

3 Answers3

5

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
  • 48,720
  • 10
  • 100
  • 148
2

Use LINQ's method Last():

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

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

Jens R.
  • 171
  • 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
  • 141,979
  • 28
  • 246
  • 306