List.Contains not working when interating through a foreach loop
<p>I have an list of FilterItems (called filter). Each FilterItem consists of a string &amp; a boolean value. e.g. "0" and false.</p>

<p>I have declared the list like so:</p>

<pre><code> List&lt;FilterItem&gt; filter = new List&lt;FilterItem&gt;();
</code></pre>

<p>I'm then iterating through a datatable column, the intention is to add every single value from that column into filter - and if a value occurs twice - don't add a repeat entry to the filter List. This is what i'm doing:</p>

<pre><code>List&lt;FilterItem&gt; filter = new List&lt;FilterItem&gt;(); //initialise new list
foreach (DataRow row in RawResults.Rows) //For each row in DT
{
    FilterItem myItem = new FilterItem { Name = row.ItemArray[i].ToString(), Checked = CheckState.Checked }; //create item
    if (!filter.Contains(myItem)) //if item doesn't exist
    {
        filter.Add(myItem); //add it
    }
}
</code></pre>

<p>The problem is that the result of Contains is always false even when myItem is identical to items already in the list - I think this is beacuse of the foreach loop - but I don't understand why because the filter List is declared outside of that loop. I've tried declaring myItem outside of the foreach loop too and that makes zero difference.</p>

<p>If I do the following: </p>

<pre><code>List&lt;FilterItem&gt; filter = new List&lt;FilterItem&gt;(); //initialise new list
foreach (DataRow row in RawResults.Rows) //For each row in DT
{
    FilterItem myItem = new FilterItem { Name = row.ItemArray[i].ToString(), Checked = CheckState.Checked }; //create item
    if (!filter.Contains(myItem)) //if item doesn't exist
    {
        filter.Add(myItem); //add it
    }
    FilterItem myItem = new FilterItem { Name = row.ItemArray[i].ToString(), Checked = CheckState.Checked }; //create item
    if (!filter.Contains(myItem)) //if item doesn't exist
    {
        filter.Add(myItem); //add it
    }
}
</code></pre>

<p>The 2nd time .Contains is called (within the same iteration of the foreach loop) it correctly goes to true, just not when the foreach loop is iterated around again. </p>