Is there a better way to write lots of repeated instances of "if(string.IsNullOrEmpty())"

Sorry if this is something that has been answered before, I wasn't really sure what to search for. I have some code which has lots of null/empty checks before executing single lines of code. It's quite ugly and I feel like there's probably a better way to do this.

Example:

private XElement getWhereXMLNode()
{
    XElement where = new XElement("where");

    if (!string.IsNullOrEmpty(County))
    {
        where.Add(new XElement("county", County));
    }
    if (!string.IsNullOrEmpty(District))
    {
        where.Add(new XElement("district", District));
    }
    if (!string.IsNullOrEmpty(Parish))
    {
        where.Add(new XElement("parishLAStyle", Parish));
    }
    if (!string.IsNullOrEmpty(ParliamentaryConstituency))
    {
        where.Add(new XElement("parCon", ParliamentaryConstituency));
    }
    if (!string.IsNullOrEmpty(GovernmentRegion))
    {
         where.Add(new XElement("govReg", GovernmentRegion));
    }
    if (!string.IsNullOrEmpty(MainQuery))
    {
        where.Add(new XElement("freetext_where", MainQuery));
    }

    return where;
}
Jon Skeet
people
quotationmark

In this case, you can use the fact that LINQ to XML ignores null values on construction. Create a small local method that takes an element name and the value, and returns either an element or null:

private XElement CreateWhereElement()
{
    return new XElement("where",
        CreateChild("county", County),
        CreateChild("district", District),
        CreateChild("parishLAStyle", Parish),
        CreateChild("parCon", ParliamentaryConstituency),
        CreateChild("govReg", GovernmentRegion),
        CreateChild("freetext_where", MainQuery));

    XElement CreateChild(string name, string value) =>
        string.IsNullOrEmpty(value) ? null : new XElement(name, value);
}

people

See more on this question at Stackoverflow