Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a canonical way to "fix" a "dynamic" IEnumerable?
    text
    copied!<p><a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx">IEnumerable</a> does not guarantee that enumerating twice will yield the same result. In fact, it's quite easy to create an example where <code>myEnumerable.First()</code> returns different values when executed twice:</p> <pre><code>class A { public A(string value) { Value = value; } public string Value {get; set; } } static IEnumerable&lt;A&gt; getFixedIEnumerable() { return new A[] { new A("Hello"), new A("World") }; } static IEnumerable&lt;A&gt; getDynamicIEnumerable() { yield return new A("Hello"); yield return new A("World"); } static void Main(string[] args) { IEnumerable&lt;A&gt; fix = getFixedIEnumerable(); IEnumerable&lt;A&gt; dyn = getDynamicIEnumerable(); Console.WriteLine(fix.First() == fix.First()); // true Console.WriteLine(dyn.First() == dyn.First()); // false } </code></pre> <p>This is not just an academic example: Using the popular <code>from ... in ... select new A(...)</code> will create exactly this situation. This can lead to unexpected behaviour:</p> <pre><code>fix.First().Value = "NEW"; Console.WriteLine(fix.First().Value); // prints NEW dyn.First().Value = "NEW"; Console.WriteLine(dyn.First().Value); // prints Hello </code></pre> <p><strong>I understand why this happens.</strong> I also know that this could be fixed by executing <code>ToList()</code> on the Enumerable or by overriding <code>==</code> for class <code>A</code>. That's not my question.</p> <p>The question is: When you write a method that takes an arbitrary IEnumerable and you want the property that the sequence is only evaluated once (and then the references are "fixed"), what's the canonical way to do this? <code>ToList()</code> seems to be used mostly, but if the source is fixed already (for example, if the source is an array), the references are copied to a list (unnecessarily, since all I need is the fixed property). Is there something more suitable or is <code>ToList()</code> the "canonical" solution for this issue?</p>
 

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