C# 添加“的巧妙方法”;当我连接两个可能为空的字符串变量时
我有一个这样做的代码:C# 添加“的巧妙方法”;当我连接两个可能为空的字符串变量时,c#,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";
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";
我想知道是否有一个小技巧可以让我以一行或更漂亮的方式生成结果消息
注意。我知道这是完全没有用的,它可能会影响可读性,我不是在寻找一个好的实践,而是寻找一个最好的技巧,使尽可能少的行
string.Join(" and ", new []{ name, love }.Where(i => !string.IsNullOrEmpty(i)))
当然,一直这样做会有点笨拙,因此您可能希望将其转化为一种扩展方法:
public static string Join(this IEnumerable<string> @this, string separator)
{
return string.Join(separator, @this.Where(i => !string.IsNullOrEmpty(i)));
}
编辑:
对于问题的第二部分(当只有一个选项时使用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)
);
}
我用N()
来表示IsNewName()
和L()
来表示IsNewLove()
,然后你可以:
result = N()? "Name" : ""
+ (N()&&L())? " and " : ""
+ L()? "Love" : ""
+ (N()&&L())? " are " : " is "
+ "updated";
这是一行,分解成一个答案
没有用,按要求。我的两分钱。无法抗拒
var names = new List<string>();
if (isNewName())
names.Add("Name");
if (isNewLove())
names.Add("Love");
var op = String.Format("{0} {1} updated.", String.Join(" and ", names), names.Count == 1 ? "is" : "are");
var name=newlist();
if(isNewName())
名称。添加(“名称”);
如果(isNewLove())
姓名。加上(“爱”);
var op=String.Format(“{0}{1}updated.”,String.Join(“and”,names),names.Count==1?“is”:“are”);
我认为这是不对的。有“是”和“是”的情况。@naveen是真的,尽管OP只要求加入,而不是“是/是”。当然,它可能在很多方面变得复杂。我有类似的代码,也处理像屈折变化之类的东西。从技术上来说,虽然标题上写着“和”,但他确实要求用一行或“更漂亮的方式”来生成结果。它涉及到检查条件。我也看不出有什么把戏:)查克·诺里斯可能会找到答案+1.anyway@naveen这只是一个很小的部分-您可以通过一个简单的helper函数或使用更好的数据类型来解决这一问题:)我认为,您的代码现在很好,但您可以将其合并到方法中以实现简单的reusing@Frank59请阅读NB。第节;)我看到人们对这个问题投了反对票,或者要求关闭它。我认为它符合发布规则中的“一个实用的、可回答的、软件开发所特有的问题”。请让我知道我是否应该改进我的问题&对不起,我的问题不好english@IggY一般来说,我们不会用“聪明”的方式来做事。您已经有了一些可以正常工作的东西-这比堆栈溢出更适合CodeReview。这个问题,正如它所写的,不适合代码审查,因为它似乎是示例代码。然而,在真实的环境中,CR很适合这种问题。哦,如果我在现实生活中没有见过这样(甚至更糟)的代码,那就好笑了:D
result = N()? "Name" : ""
+ (N()&&L())? " and " : ""
+ L()? "Love" : ""
+ (N()&&L())? " are " : " is "
+ "updated";
var names = new List<string>();
if (isNewName())
names.Add("Name");
if (isNewLove())
names.Add("Love");
var op = String.Format("{0} {1} updated.", String.Join(" and ", names), names.Count == 1 ? "is" : "are");