Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C# collections always enforce order?

I.E. If I want to select from an array, is the resultant IEnumerable<object> object necessarily in order?

public class Student { public string FullName, ... }
public class School { public string Name, public Student[] Students, ... }

public void StudentListWork(School thisSchool)
{
    IEnumerable<string> StudentNames = thisSchool.Students.Select(student => student.FullName);

    // IS StudentNames GUARANTEED TO BE IN THE SAME ORDER AS thisSchool.Students?
}

Thanks!

like image 321
ArtOfTheSmart Avatar asked Aug 14 '11 22:08

ArtOfTheSmart


People also ask

What is the do command in C?

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

What is a Do While loop in C?

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Do While vs while loop?

What is a do-while loop? The do-while loop is very similar to that of the while loop. But the only difference is that this loop checks for the conditions available after we check a statement. Thus, it is an example of a type of Exit Control Loop.

Do While loop in C simple example?

printf("%d * %d = %d\n", N, i, N * i); statement is used to print the multiplication table of N. In the above example, we have taken N to be 5. i will go from 1 to 10 using the update expression i++;. At each iteration/repetition the print statement will be executed with an increased i value.


1 Answers

Yes, in this case:

  • Arrays returns items in the natural order
  • Enumerable.Select returns items in the order of the original sequence (after projection, of course)

Some collections do not retain order, however. In particular:

  • Collections such as HashSet<T> and Dictionary<TKey, TValue> make no guarantees about the order in which values are returned
  • Collections such as SortedSet<T> and SortedDictionary<TKey, TValue> apply guaranteed ordering based on the items placed within them
like image 184
Jon Skeet Avatar answered Oct 19 '22 20:10

Jon Skeet