C#集合总是强制执行订单吗?

Art*_*art 13 .net c# collections

IE如果我想从数组中选择,结果IEnumerable<object>对象是否必须按顺序排列?

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?
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jon*_*eet 16

是的,在这种情况下:

  • 数组以自然顺序返回项目
  • Enumerable.Select 按原始序列的顺序返回项目(当然,在投影之后)

但是,有些集合保留订单.特别是:

  • 集合,例如HashSet<T>并且Dictionary<TKey, TValue>不保证返回值的顺序
  • 根据放置在其中的项目,收集SortedSet<T>SortedDictionary<TKey, TValue>应用保证订购