Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# array get last item from split in one line

Tags:

arrays

c#

.net

I know that this works to get the first item of an array

string aString = @"hello/all\this\is/a\test";
string firstItemOfSplit = aString.Split(new char[] {'\\', '/'})[0];
//firstItemOfSplit = hello

is there a way to get the last item? Something like

string aString = @"hello/all\this\is/a\test";
string lastItemOfSplit = aString.Split(new char[] {'\\', '/'})[index.last];
//lastItemOfSplit = test
like image 257
Patrick Lorio Avatar asked Oct 18 '11 21:10

Patrick Lorio


Video Answer


1 Answers

You could always use LINQ:

string lastItem = aString.Split(...).Last();

Note that Enumerable.Last() is optimized when working on an IList<T> and you're not applying a predicate - so it's not even going to walk over the sequence to find the last one. (Not that it's likely to be an issue anyway.)

like image 137
Jon Skeet Avatar answered Sep 19 '22 07:09

Jon Skeet