You can do this with pattern matching:
var result = s.Split(' ') is var names && names.Length > 1 ?
new Tuple<string, string>(string.Join(" ", names.Take(names.Length - 1)), names.Last()) :
new Tuple<string, string>(displayName, string.Empty);
The var
pattern is a catch-all for any type or value.
(I turned your calls to .Count()
into .Length
, as it's more idiomatic for arrays).
I'd recommend using ValueTuple instead of Tuple<T>
:
var result = s.Split(' ') is var names && names.Length > 1 ?
(string.Join(" ", names.Take(names.Length - 1)), names.Last()) :
(displayName, string.Empty);
Using C# 8's ranges, you can write this as:
var result = s.Split(' ') is var names && names.Length > 1 ?
(string.Join(" ", names[0..^1]), names[^1]) :
(displayName, string.Empty);
(Note that splitting names using string.Split
might not be the best way, and splitting them at all is probably a bad idea! See the other excellent answers here).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…