【问题标题】:Do C# collections always enforce order?C# 集合是否总是强制执行顺序?
【发布时间】:2011-08-14 22:38:53
【问题描述】:

I.E.如果我想从数组中进行选择,结果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?
}

谢谢!

【问题讨论】:

  • 什么是学生?一个列表?排序列表?数组?一本字典? “收藏”是一个广义的术语,它们具有不同的特点。
  • @Mystere:根据第二行,它是一个数组。
  • @Jon Skeet-Doh!错过了……
  • 有序集合的 IEnumerable 实现不会竭尽全力以无序序列返回项目。不保证,只是马感。你可以依赖它,它不会被破坏。

标签: c# .net collections


【解决方案1】:

是的,在这个的情况下:

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

然而,有些集合不保持顺序。特别是:

  • HashSet&lt;T&gt; 和 Dictionary&lt;TKey, TValue&gt; 等集合不保证返回值的顺序
  • SortedSet&lt;T&gt; 和 SortedDictionary&lt;TKey, TValue&gt; 等集合根据放置在其中的项目应用保证排序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2011-06-25
    • 1970-01-01
    相关资源
    最近更新 更多