是否有更好的方法来编写大量重复的" if(string.IsNullOrEmpty())"

时间:2017-11-17 13:52:27

标签: c# .net refactoring

很抱歉,如果这是之前已经回答的问题,我不确定要搜索什么。我有一些代码在执行单行代码之前有很多空/空检查。这很难看,我觉得这可能是一个更好的方法。

示例:

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;
}

1 个答案:

答案 0 :(得分:4)

在这种情况下,您可以使用LINQ to XML在构造时忽略空值的事实。创建一个小的本地方法,它接受一个元素名称和值,并返回一个元素或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);
}