[英]Is there an elegant/built-in method in C# to add a string connector IFF two strings have length > 0?
I know I can do this via an extension (and I do so with StringBuilder
), but as often as I need it I feel like there has to be a better way. 我知道我可以通过扩展来做到这一点(而且我可以使用
StringBuilder
做到这一点),但是我经常需要一种更好的方法。 Let's say I am combining a first and last name, either of which may be missing (null or empty, don't care), I only want a space if both are present. 假设我要组合一个姓氏和名字,这两个名字中的任何一个都可能丢失(null或空,不在乎),如果两个都存在,我只想要一个空格。 So
所以
return firstName + (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName) ? " " : string.Empty) + lastName;
gives me Joe Smith
but never Joe[trailingspace]
or [leadingspace]Smith
. 给了我
Joe Smith
却没有给Joe Smith
Joe[trailingspace]
或[leadingspace]Smith
。
Obviously this is a silly example, but I do this constantly in the Real World. 显然,这是一个愚蠢的例子,但是我在现实世界中经常这样做。 Any better ideas?
还有更好的主意吗?
EDIT : Don't suggest String.Join. 编辑 :不建议String.Join。 It doesn't work.
没用 (Well, unless you combine it with LINQ, as spender does below.)
(好吧,除非您将它与LINQ结合使用,如下面的支出者所述。)
I'd go with something like: 我会选择类似的东西:
public static string JoinNonEmpty(string separator, params string[] values)
{
return
string.Join(separator, values.Where(v => !string.IsNullOrEmpty(v)));
}
From this blog String.Join method? 从这个博客的String.Join方法? , you could create an extension method that takes in an array and separator?:
,您可以创建一个采用数组和分隔符的扩展方法?:
string[] input = {"Joe", null, "Smith"};
return input.Aggregate((x,y)=>String.IsNullOrEmpty(y)?x :String.Concat(x, " ", y));
Personally I would use string.Format(): 我个人将使用string.Format():
var myName = string.Format( "{0}{1}{2}"
, firstName
, !string.IsNullEmptyOrwhitespace(firstName) && !string.IsNullEmptyOrWhitespace(lastName) ? " " : string.empty
, lastName
);
This is not clever code relying on LINQ or extension methods, it is a standard, basic and straight forward method of doing it - importantly you can see instantly what is happening and what the result should be. 这不是依靠LINQ或扩展方法的聪明代码,它是一种标准,基本且直接的方法-重要的是,您可以立即看到正在发生的事情以及应该取得的结果。 Using an extension method becomes more relevant if you are looking to do the same operation in many different places.
如果您希望在许多不同的地方进行相同的操作,则使用扩展方法将变得更加重要。
Alternatively, your data object could encapsulate this logic: 或者,您的数据对象可以封装以下逻辑:
public class MyData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get { /*insert the string.Format() illustrated above */ }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.