聪明的方法添加"和*当我连接两个可能为空的字符串变量

Igg*_*ggY -1 c#

我有一个代码这样做:

if (isNewName())
    name = "newName";
if (isNewLove())
    love = "newLove";

//Generate output message
if (isNewName() && isNewLove)
    result = "Name and Love are updated"
else if (isNewName())
    result = "Name is updated";
else if (isNewLove())
    result = "Love is updated";
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一个小技巧可以让我在一行中生成结果消息,或者以更漂亮的方式生成结果消息.

NB.我知道它完全没用,它可能会影响可读性,我不是在寻找一个好的做法,而只是为了尽可能减少线路的最佳技巧.

Lua*_*aan 5

string.Join(" and ", new []{ name, love }.Where(i => !string.IsNullOrEmpty(i)))
Run Code Online (Sandbox Code Playgroud)

当然,一直这样做会有点笨拙,所以你想把它变成一个扩展方法:

public static string Join(this IEnumerable<string> @this, string separator)
{
  return string.Join(separator, @this.Where(i => !string.IsNullOrEmpty(i)));
}
Run Code Online (Sandbox Code Playgroud)

您可以将其用作例如:

new  []{ name, love }.Join(" and ");
Run Code Online (Sandbox Code Playgroud)

编辑:

对于问题的第二部分(使用is时只有一个选项,are当有多个选项时),您可以使用例如:

public static string Join(this IEnumerable<string> @this, string separator, 
  string singleFormat, string multipleFormat)
{
  var nonEmpty = @this.Where(i => !string.IsNullOrEmpty(i)).ToArray();

  return string.Format
    (
      nonEmpty.Count == 1 ? singleFormat : multipleFormat, 
      string.Join(separator, nonEmpty)
    );
}
Run Code Online (Sandbox Code Playgroud)

被称为:

new [] { name, love }.Join(" and ", "{0} is updated", "{1} are updated");
Run Code Online (Sandbox Code Playgroud)

  • 我不认为这是正确的.有的情况是也是. (5认同)