如果变量的值不在忽略列表中,则运行函数

时间:2015-05-15 21:30:56

标签: c# .net

如果变量的值不等于我设置的忽略列表中的某个值,我试图弄清楚如何运行代码块。

        List<Variance> variancesList = new List<Variance>();
        PropertyInfo[] fieldList = saveModel.GetType().GetProperties();
        foreach (PropertyInfo field in fieldList)
        {
            if (!placeholder)
            {
                Variance variance = new Variance();
                variance.property = field.Name;
                variance.saveValue = field.GetValue(saveModel, null);
                variance.loadValue = field.GetValue(loadModel, null);
                if (!Equals(variance.saveValue, variance.loadValue))
                    variancesList.Add(variance);
            }
        }

我想用一个列表检查替换占位符,如果列表中有属性名称,它应该跳过比较。

有什么想法吗?谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

这可以通过HashSet很好地完成:

HashSet<string> ignores = new HashSet<string>();
ignores.Add("ANameToIgnore");
ignores.Add("AnotherNameToIgnore");

List<Variance> variancesList = new List<Variance>();
PropertyInfo[] fieldList = saveModel.GetType().GetProperties();
foreach (PropertyInfo field in fieldList)
{
    if (!ignores.Contains(field.Name))
    {
        Variance variance = new Variance();
        variance.property = field.Name;
        variance.saveValue = field.GetValue(saveModel, null);
        variance.loadValue = field.GetValue(loadModel, null);
        if (!Equals(variance.saveValue, variance.loadValue))
            variancesList.Add(variance);
    }
}

答案 1 :(得分:0)

您可以使用.contains检查属性(请参阅下面的示例代码)

var placeholder= new List<string>();
    placeholder.Add("Name");
    placeholder.Add("LastName");
    placeholder.Add("Salary");

if (placeholder.Contains("Name"))
{
  Variance variance = new Variance();
 ....    
}