C#foreach循环-是否保证顺序*稳定性*? [英] C# foreach loop - is order *stability* guaranteed?

查看:466
本文介绍了C#foreach循环-是否保证顺序*稳定性*?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个给定的收藏.从未以任何方式更改集合,我使用foreach遍历了其内容两次.除宇宙射线外,是否绝对可以保证两个循环中的顺序是一致的?

Suppose I have a given collection. Without ever changing the collection in any way, I loop through its contents twice with a foreach. Barring cosmic rays and what not, is it absolutely guaranteed that the order will be consistent in both loops?

或者,给定HashSet<string>包含许多元素,是什么导致以下注释行的输出不相等:

Alternatively, given a HashSet<string> with a number of elements, what can cause the output from the the commented lines in the following to be unequal:

{
    var mySet = new HashSet<string>();
    // Some code which populates the HashSet<string>

    // Output1
    printContents(mySet);

    // Output2
    printContents(mySet);
}

public void printContents(HashSet<string> set) {
    foreach(var element in set) {
         Console.WriteLine(element);
    }
}

如果我能得到一个一般性的答案来解释什么导致实现不符合上述标准,这将是有帮助的.不过,具体来说,我对DictionaryList和数组感兴趣.

It would be helpful if I could get a general answer explaining what causes an implementation to not meet the criteria described above. Specifically, though, I am interested in Dictionary, List and arrays.

推荐答案

数组枚举保证顺序.

ListList<T>有望提供稳定的顺序(因为它们有望实现顺序索引的元素).

List and List<T> are expected to provide stable order (since they are expected to implement sequentially-indexed elements).

字典,HashSet明确不保证顺序. 2个接一个的彼此迭代的调用不太可能以不同的顺序返回项目,但是没有保证或期望.不应期望任何特定的命令.

Dictionary, HashSet are explicitly do not guarantee order. Its is very unlikely that 2 calls to iterate items one after each other will return items in different order, but there is no guarantees or expectations. One should not expect any particular order.

Dictionary/HashSet的排序版本按排序顺序返回项目.

Sorted versions of Dictionary/HashSet return items in sort order.

其他IEnumerable对象可以自由地执行其所需的任何操作.通常,以符合用户期望的方式来实现迭代器. IE.如果提供了显式顺序,则具有隐式顺序的事物的枚举应是稳定的-预期是稳定的.对未指定顺序的数据库查询应该以半随机顺序返回项目.

Other IEnumerable objects are free to do whatever they want. Normally one implements iterators in such a way that it matches user's expectations. I.e. enumeration of something that have implicit order should be stable, if explicit order provided - expected to be stable. Query to database that does not specify order should be expected to return items in semi-random order.

检查此问题以获取链接:

Check this question for links: Does the foreach loop in C# guarantee an order of evaluation?

这篇关于C#foreach循环-是否保证顺序*稳定性*?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆