一行在C#中声明,比较并返回 [英] One line declare, compare and return in c#

查看:86
本文介绍了一行在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)) ;

其中namesname.Split(' ')的结果.

如果不将其声明为像这样的单独行,则无法获得该结果:

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

var names = name.Split(' ');

这行是我想要避免的,但我也不想在每次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?

非常感谢您.

推荐答案

您可以通过模式匹配:

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

var模式是所有类型或值的全部.

The var pattern is a catch-all for any type or value.

(我将您对.Count()的调用转换为.Length,因为它对数组来说更惯用了.)

(I turned your calls to .Count() into .Length, as it's more idiomatic for arrays).

我建议使用 ValueTuple 代替Tuple<T>:

var result = s.Split(' ') is var names && names.Length > 1 ? 
    (string.Join(" ", names.Take(names.Length - 1)), names.Last()) :
    (displayName, string.Empty);

使用 C#8范围,您可以将其写为:

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

(请注意,使用string.Split拆分名称可能不是最好的方法,而完全拆分名称可能是个坏主意!请参见此处的其他出色答案).

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

这篇关于一行在C#中声明,比较并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆