Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think the order of elements retrieved by a <code>LINQ</code> is preserved, at least for <code>LINQ to Object</code>, for <code>LINQ to SQL or Entity</code>, it may depend on the order of the records in the table. For <code>LINQ to Object</code>, I'll try explaining why it preserves the order. </p> <p>In fact when the <code>LINQ</code> query is executed, the <code>IEnumerable</code> source will call to <code>GetEnumerator()</code> to start looping with a <code>while loop</code> and get the next element using <code>MoveNext()</code>. This is how a <code>foreach</code> works on the <code>IEnumerable</code> source. We all know that a <strong><code>foreach</code> will preserve the order of the elements</strong> in a list/collection. Digging more deeply into the <code>MoveNext()</code>, I think it just has some <code>Position</code> to save the current <code>Index</code> and <code>MoveNext()</code> just increase the <code>Position</code> and <code>yield</code> the corresponding element (at the new position). That's why it should preserve the order, <strong>all the code changing the original order is redundant or by explicitly calling to <code>OrderBy</code> or <code>OrderByDescending</code></strong>.</p> <p>If you think this </p> <pre><code>int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; foreach(var i in numbers) if(i &lt; 5) Console.Write(i + " "); </code></pre> <p>prints out <code>4 1 3 2 0</code> you should think this</p> <pre><code>int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; IEnumerator ie = numbers.GetEnumerator(); while(ie.MoveNext()){ if((int)ie.Current &lt; 5) Console.Write(ie.Current + " "); } </code></pre> <p>also prints out <code>4 1 3 2 0</code>. Hence this <code>LINQ</code> query </p> <pre><code>var lowNums = from n in numbers where n &lt; 5 select n; foreach (var i in lowNums) { Console.Write(i + " "); } </code></pre> <p>should also print out <code>4 1 3 2 0</code>.</p> <p><strong>Conclusion:</strong> The order of elements in <code>LINQ</code> depends on how <code>MoveNext()</code> of an <code>IEnumerator</code> obtained from an <code>IEnumerable</code> is implemented. However, it's for sure that <strong>the order of elements in <code>LINQ</code> result will be the same order a <code>foreach</code> loop works on the elements</strong>.</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.
    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