简体   繁体   中英

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

return firstName + (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName) ? " " : string.Empty) + lastName;

gives me Joe Smith but never Joe[trailingspace] or [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. It doesn't work. (Well, unless you combine it with LINQ, as spender does below.)

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? , 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():

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. 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 */ }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM