14

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!

ArtOfTheSmart
  • 330
  • 2
  • 12

1 Answers1

18

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
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194