我可以使这段代码更简单,更小吗?

时间:2018-04-27 10:32:15

标签: c#

正如您在下面的代码中看到的,我有3个foreach语句,我认为它有点像大代码。主要区别仅在于FieldName。我希望有人能让它变得更简单..

string fieldname;
string fieldLabel = "";

foreach (var u in data)
{
    fieldname = "field" + tag.getName() + "[" + msg.getMtId().getMessageType() + "]" + ".name";
    if (u.Key == fieldname)
    {
        fieldLabel = u.Value.ToString();
    }
}

if (fieldLabel == "")
{
    fieldname = "field" + tag.getName() + ".name";
    foreach (var u in data)
    {
        if (u.Key == fieldname)
        {
            fieldLabel = u.Value.ToString();
        }
        if (fieldLabel == "")
        {
            fieldname = "field" + tag.getName() + ".name";
        }
    }
}

if (fieldLabel == "")
{
    fieldname = "field" + tag.getName()+ "[" + msg.getMtId().getMessageType() + "]" + ".components";
    foreach (var u in data)
    {
        if (u.Key == fieldname)
        {
            fieldLabel = u.Value.ToString();
        }
    }
}

3 个答案:

答案 0 :(得分:1)

确认数据是字典:

string fieldname = "field" + tag.getName() + "[" + msg.getMtId().getMessageType() + "]" + ".name";
string fieldLabel = "";

if(!data.ContainsKey(fieldname))
    fieldname = "field" + tag.getName() + ".name";
if (!data.ContainsKey(fieldname))
    fieldname = "field" + tag.getName() + "[" + msg.getMtId().getMessageType() + "]" + ".components";
if (data.ContainsKey(fieldname))
    fieldLabel = data[fieldname].ToString();

答案 1 :(得分:1)

FirstOrDefault函数将返回满足给定顺序条件的第一个keyValuePair的值。

var fieldLabel = "";

var foundValue = data.Where(kvp => kvp.Key == "field" + tag.getName() + "[" + msg.getMtId().getMessageType() + "]" + ".name"
                                || kvp.Key == "field" + tag.getName() + ".name"
                                || kvp.Key == "field" + tag.getName() + "[" + msg.getMtId().getMessageType() + "]" + ".components")
                     .Select(e => (string)e.Value)
                     .FirstOrDefault();

if (!string.IsNullOrEmpty(foundValue))
    fieldLabel = foundValue;

答案 2 :(得分:0)

你可以试试这个:

string fieldLabel = "";
string[] fieldnames = {
    "field" + tag.getName() + "[" + msg.getMtId().getMessageType() + "]" + ".name",
    "field" + tag.getName() + ".name",
    "field" + tag.getName()+ "[" + msg.getMtId().getMessageType() + "]" + ".components"
};

foreach (var fieldname in fieldnames)
{
    foreach (var u in data)
    {
        if (u.Key == fieldname)
        {
            fieldLabel = u.Value.ToString();
        }
    }
    if (fieldLabel != "") break;
}

甚至更短:

string fieldLabel = "";
string[] fieldnames = {
    "field" + tag.getName() + "[" + msg.getMtId().getMessageType() + "]" + ".name",
    "field" + tag.getName() + ".name",
    "field" + tag.getName()+ "[" + msg.getMtId().getMessageType() + "]" + ".components"
};

foreach (var fieldname in fieldnames)
{
    if (data.ContainsKey(fieldname))
    {
        fieldLabel = data[fieldname].ToString();
        break;
    }
}