Join with Line Breaks C# ASP.net

Something I often come across is having to display database fields such as address1,address2,address3,address4,postcode, etc. You’ll want to display this nicely with line breaks but no gaps.  This is a useful routine to use:


public string JoinWithLineBreaks(params string[] strings)
{
    return String.Join("<br />", strings.Where(s => !String.IsNullOrEmpty(s)));
}

You’ll probably want to encode your output:


public static string JoinWithLineBreaks(params string[] strings)
{
    return String.Join("<br />", strings.Where(s => !String.IsNullOrEmpty(s)).Select(s =>  Server.HtmlEncode(s)));
}

Use it like this…


literalDisplayAddress.Text = r.Name + JoinWithLineBreaks(r.Address1, r.Address2, r.Address3, r.Address4, r.Zip);

Posted in : Technology

Leave a Reply