C#集合总是强制执行订单吗?
IE如果我想从数组中选择,生成的IEnumerable
对象是否必然按顺序排列?
public class Student { public string FullName, ... } public class School { public string Name, public Student[] Students, ... } public void StudentListWork(School thisSchool) { IEnumerable StudentNames = thisSchool.Students.Select(student => student.FullName); // IS StudentNames GUARANTEED TO BE IN THE SAME ORDER AS thisSchool.Students? }
谢谢!
是的,在这种情况下:
- 数组以自然顺序返回项目
-
Enumerable.Select
按原始序列的顺序返回项目(当然,在投影之后)
但是,有些馆藏不保留订单。 特别是:
- 诸如
HashSet
和Dictionary
集合不保证返回值的顺序 -
SortedSet
和SortedDictionary
等集合根据放置在其中的项目应用保证排序