Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

lambda - One line declare, compare and return in c#

I am wondering if is possible to do something like the following code:

_ = name.Split(' ') => names.Count() > 1 ?
                new Tuple<string, string>(string.Join(" ", names.Take(names.Count() - 1)), names.Last()) :
                new Tuple<string, string>(name, string.Empty)) ;

where names is the result of name.Split(' ').

Im not getting how to acces to this result without declaring it in a separated line like:

var names = name.Split(' ');

This line is what I want to avoid but also I dont want to call every time the Split function.

Anyone know how to resolve this or if it is even possible?

Thank you very much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...