Home > Enterprise >  Include only if a variable is not empty
Include only if a variable is not empty

Time:08-31

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!

CodePudding user response:

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

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

CodePudding user response:

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

or

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