Select last element quickly after a .Split() Select last element quickly after a .Split() arrays arrays

Select last element quickly after a .Split()


If you're using .NET 3.5 or higher, it's easy using LINQ to Objects:

stringCutted = myString.Split('/').Last();

Note that Last() (without a predicate) is optimized for the case where the source implements IList<T> (as a single-dimensional array does) so this won't iterate over the whole array to find the last element. On the other hand, that optimization is undocumented...


stringCutted=myString.Split("/").Last()

But, just FYI, if you're trying to get a filename from a path, this works heaps better:

var fileName=System.IO.Path.GetFileName("C:\\some\path\and\filename.txt"); // yields: filename.txt


Since you want a solution that returns the last element directly, quickly, without store the splitted array, i think this may be useful:

stringCutted = myString.Substring(myString.LastIndexOf("/")+1);