vendredi 20 février 2015

How to write elegant string join condition to get full address property

I am using ASP .NET MVC (C#). Wondering how to write elegant condition for geting full address string from address elements. Final FullAddress string should be like this:

"Street HouseNumber, ZIP City"

For instance "Krakonova 23, 12300 Prague"

(But of course, the user can enter only the City too - full address is not required)


I have this model:



public class Address
{
public int ID { get; set; }
public string Street { get; set; }
public string HouseNo { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string FullAddress
{
get
{
string _fullAddress = null;
// (...)
return _fullAddress;
}
}




For instance I am thinking about something like:

get
{
string[] _addressPartOne = { this.Street, this.HouseNo };
string[] _addressPartTwo = { this.Zip, this.City };
string[] _addressFinal = { string.Join(" ", _addressPartOne.Where(s => !String.IsNullOrEmpty(s))), string.Join(" ", _addressPartTwo.Where(s => !String.IsNullOrEmpty(s)))};
string _fullAddress = string.Join(", ", _addressFinal.Where(s => !String.IsNullOrEmpty(s)));
return _fullAddress;
}

Aucun commentaire:

Enregistrer un commentaire