Note that there are some explanatory texts on larger screens.

plurals
  1. POReturn value of IEnumerable<T>.Contains changes if called multiple times
    primarykey
    data
    text
    <p>I'm having trouble understanding why multiple calls of Contains <strong>return different values for the same parameter on the same enumerable</strong>. While I understand that the collection can be modified, thus changing the result in a subsequent call, this can be ruled out here.</p> <p>Consider the following (stripped-down) code in an MVC view. The purpose of this will be to display a list of checkboxes (as there's no HTML-helper for that), and determining through the model's properties which ones should be checked when opening the view.</p> <pre><code>@foreach (var d in Model.AllDomains) { bool isChecked = Model.Project.Domains.Contains(d.ID); &lt;input @(isChecked ? "checked=\"checked\" " : "")type="checkbox" value="@d.ID" /&gt; // more stuff here } </code></pre> <p>Changing this to use an actual List makes the whole thing work as expected:</p> <pre><code>var tmp = Model.Project.Domains.ToList(); @foreach (var d in Model.AllDomains) { bool isChecked = tmp.Contains(d.ID); &lt;input @(isChecked ? "checked=\"checked\" " : "")type="checkbox" value="@d.ID" /&gt; // more stuff here } </code></pre> <p>The following is the model that is bound to my view (again simplified to make it more readable):</p> <pre><code>public ProjectVM GetByID(int id) { return new ProjectVM { Project = new Project { ... // Other properties here Domains = from d in MyObjectModel.Projects[id].Domains select d.ID }, AllDomains = from d in MyObjectModel.Domains orderby d.Name select new { ID = d.ID, Name = d.Name } }; } </code></pre> <p>Now, while from debugging I know that <code>Model.Project.Domains</code> will contain the correct number of entries, as well as the correct values, calling .Contains() on the method returns an <strong>arbitrary result</strong> - either true or false.</p> <p>In fact, if I put the line with the Contains() call into the debugger's "Watch" tab multiple times, even with an hard coded argument (e.g. 4) <strong>the result will alternate from <code>true</code> to <code>false</code></strong> with every call.</p> <p><strong>What is happening here, what am I overlooking?</strong></p> <p>Because of the way that Model.Project.Domains is instantiated, its actual type is a <code>WhereSelectEnumerableIterator&lt;T&gt;</code>, but this implements <code>IEnumerable&lt;T&gt;</code> so that shouldn't be an issue...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload