0

I was trying to figure out how to run a block of code if the value of a variable is not equal to some value in an ignore list I've set up.

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

I'd like to replace placeholder with a check against a list, where if a property name is in the list, it should skip over the comparison.

Any ideas? Thanks for the assistance.

2
  • if( !IgnoreList.Contains(value) ) { ... } Commented May 15, 2015 at 21:32
  • if( variancesList.Any( v=>v.property = field.Name) ) Commented May 15, 2015 at 21:44

2 Answers 2

1

This can be accomplished nicely with a 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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, HashSets perform better than Lists if they contain many items. HashSets = constant access time O(1).
0

You can use the .contains to check the property (see below sample code)

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.