ThatBrianDude
ThatBrianDude

Reputation: 3190

Is there a way to get the length of a return value in the same line of code?

I'm not sure if I worded that right but heres what I'm looking for.

I would like to do something like this:

string lastWord = words.Split(':')[splitResult.Length -1];

Is there any way to make that happen or must I store the array first?

Upvotes: 0

Views: 62

Answers (1)

Hari Prasad
Hari Prasad

Reputation: 16986

using Linq, LastOrDefault extention.

string lastword = words.Split(':').LastOrDefault();

If I would use Split, wouldnt I be splitting it twice?

It Depends.

if you do below, yes you are splitting twice.

string lastWord = words.Split(':')[words.Split(':').Length -1];

and if you use temporary variable for splits then you need Split only once.

var splits =words.Split(':');
string lastWord = splits[splits.Length -1];

Upvotes: 8

Related Questions