A simple C# LINQ method to put an address on one line separated by commas

Posted written by Paul Seal on November 10, 2017 C#

This post gives you a simple way of getting an address on one line, separated by commas and it ignores any blank lines.

public class Address
{
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string PostCode { get; set; }
    public string Country { get; set; }

    public string OnOneLine => string.Join(", ", ((new List() { Line1, Line2, City, County, PostCode, Country })).Where(x => !string.IsNullOrEmpty(x)));
}

So now you can test it like this.

Address test1 = new Address() { Line1 = "10 Street Name", Line2 = "Smallville", City = "Big City", County = "Shire", PostCode = "WC1 1DN", Country = "United Kingdom" };
Console.WriteLine(test1.OnOneLine);
//returns: 10 Street Name, Smallville, Big City, Shire, WC1 1DN, United Kingdom

Address test2 = new Address() { Line1 = "10 Street Name", City = "Big City", PostCode = "WC1 1DN", Country = "United Kingdom" };
Console.WriteLine(test2.OnOneLine);
//returns: 10 Street Name, Big City, WC1 1DN, United Kingdom

Address test3 = new Address() { Line1 = "10 Street Name", Line2 = "Smallville", PostCode = "WC1 1DN" };
Console.WriteLine(test3.OnOneLine);
//returns: 10 Street Name, Smallville, WC1 1DN