Darkmatter5
Darkmatter5

Reputation: 1249

Include only if a variable is not empty

In my code FirstName and LastName always has values, but MiddleName does not always, so my question is how can I best create an additional string of concatenating the three variables, but not including MiddleName if MiddleName does not have a value.

Here's my code so far, but this is so long winded and I know can be simplified.

if (newContributor.MiddleName == "")
{
  newContributor.Url =
  newContributor.FirstName.Replace(" ", "-").ToLower() + "-" +
  newContributor.LastName.Replace(" ", "-").ToLower();
}
else
{
  newContributor.Url =
  newContributor.FirstName.Replace(" ", "-").ToLower() + "-" +
  newContributor.MiddleName.Replace(" ", "-").ToLower() + "-" +
  newContributor.LastName.Replace(" ", "-").ToLower();
}

What would you all suggest?

Thanks!

Upvotes: 0

Views: 338

Answers (4)

Eliseo
Eliseo

Reputation: 57999

Another one

newContributor.Url=[firstName,middleName,lastName ]
                    .filter(p=>p)
                    .join("-")
                    .replace(" ","-")

Upvotes: 1

Brian Parker
Brian Parker

Reputation: 14593

You said only the middle name will be null. I also like to test for white space so I have used IsNullOrWhiteSpace

As a property in your class:

class Contributer
{
    ...
    [Required]
    public string FirstName { get; set; }

    public string? MiddleName { get; set; }

    [Required]
    public string LastName { get; set; }

    public string Url => GetUrl();

    private string GetUrl() => GetHyphenatedName()
       .Replace(oldChar: ' ', newChar: '-')
       .ToLower();

    private string GetHyphenatedName() => string.IsNullOrWhiteSpace(MiddleName) ?
            $"{FirstName}-{LastName}" :
            $"{FirstName}-{MiddleName}-{LastName}";

}

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273572

string[] parts = { firstName, middleName, lastName };
url = string.Join('-', parts.Where(p => !string.IsNullOrWhitespace(p)))
   .ToLower()
   .Replace(' ', '-');

You can make that 1 statement but that's not very readable.

In addition, you may want to handle all other 'invalid' chars with

url = System.Web.HttpUtility.UrlEncode(url);

Upvotes: 5

Martin Heralecký
Martin Heralecký

Reputation: 5789

string url = (firstName + (middleName != "" ? "-" + middleName : "") + "-" + lastName)
    .Replace(" ", "-")
    .ToLower();

or

string url = string.Join('-', new[] {firstName, middleName, lastName}.Where(p => p != ""))
    .Replace(" ", "-")
    .ToLower();

Upvotes: 0

Related Questions