每个循环的 C# 以什么顺序迭代 List

发布于 2024-08-12 10:08:32 字数 1181 浏览 2 评论 0原文

我想知道 C# 中的 foreach 循环遍历 System.Collections.Generic.List对象的顺序。

我发现关于同一主题的另一个问题 ,但我觉得它并不能令我满意地回答我的问题。

有人说没有定义顺序。但正如其他人所说,它遍历数组的顺序是固定的(从 0 到 Length-1)。 8.8.4 foreach 语句

这也是说这同样适用于任何具有顺序的标准类(例如List)。我找不到任何文档来支持这一点。因此,据我所知,它现在可能会像这样工作,但也许在下一个 .NET 版本中它会有所不同(尽管这可能不太可能)。

我还查看了 List(t).Enumerator 文档没有运气。

另一个相关问题指出,对于Java,文档中特别提到:

List.iterator()返回此列表中元素的迭代器 按正确的顺序。”

我正在 C# 文档中寻找类似的内容。

提前致谢。

编辑:感谢大家的所有回答(令人惊讶的是我很快就得到了这么多回复)。我从所有答案中了解到的内容是 List 总是按照其索引的顺序进行迭代,但我仍然希望看到一个清晰的文档说明这一点,类似于 List 上的 Java 文档。

I was wondering about the order that a foreach loop in C# loops through a System.Collections.Generic.List<T> object.

I found another question about the same topic, but I do not feel that it answers my question to my satisfaction.

Someone states that no order is defined. But as someone else states, the order it traverses an array is fixed (from 0 to Length-1). 8.8.4 The foreach statement

It was also said that the same holds for any standard classes with an order (e.g. List<T>). I can not find any documentation to back that up. So for all I know it might work like that now, but maybe in the next .NET version it will be different (even though it might be unlikely).

I have also looked at the List(t).Enumerator documentation without luck.

Another related question states that for Java, it is specifically mentioned in the documentation:

List.iterator()returns an iterator over the elements in this list
in proper sequence."

I am looking for something like that in the C# documentation.

Thanks in advance.

Edit: Thank you for all you for all your answers (amazing how fast I got so many replies). What I understand from all the answers is that List<T> does always iterate in the order of its indexing. But I still would like to see a clear peace of documentation stating this, similar to the Java documentation on List.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

梦幻的味道 2024-08-19 10:08:32

基本上,这取决于 IEnumerator 实现 - 但对于 List ,它将始终按列表的自然顺序排列,即与索引器的顺序相同:< code>list[0]、list[1]list[2] 等。

我不相信它被明确记录 - 至少,我没有没有找到这样的文档 - 但我认为你可以将其视为保证。对该顺序的任何更改都会毫无意义地破坏各种代码。事实上,我会惊讶地看到任何违反此规定的 IList 实现。诚然,很高兴看到它被专门记录......

Basically it's up to the IEnumerator implementation - but for a List<T> it will always go in the natural order of the list, i.e. the same order as the indexer: list[0], list[1], list[2] etc.

I don't believe it's explicitly documented - at least, I haven't found such documentation - but I think you can treat it as guaranteed. Any change to that ordering would pointlessly break all kinds of code. In fact, I'd be surprised to see any implementation of IList<T> which disobeyed this. Admittedly it would be nice to see it specifically documented...

所有深爱都是秘密 2024-08-19 10:08:32

Microsoft 参考源页面上的 List< ;T> 枚举器明确指出迭代是从 0 到 Length-1 完成的:

internal Enumerator(List<T> list) {
    this.list = list;
    index = 0;
    version = list._version;
    current = default(T);
}

public bool MoveNext() {

    List<T> localList = list;

    if (version == localList._version && ((uint)index < (uint)localList._size)) 
    {                                                     
        current = localList._items[index];                    
        index++;
        return true;
    }
    return MoveNextRare();
}

希望它仍然与某人相关

On Microsoft Reference Source page for List<T> Enumerator it is explicitly stated that the iteration is done from 0 to Length-1:

internal Enumerator(List<T> list) {
    this.list = list;
    index = 0;
    version = list._version;
    current = default(T);
}

public bool MoveNext() {

    List<T> localList = list;

    if (version == localList._version && ((uint)index < (uint)localList._size)) 
    {                                                     
        current = localList._items[index];                    
        index++;
        return true;
    }
    return MoveNextRare();
}

Hope it's still relevant for somebody

暮年 2024-08-19 10:08:32

在您的链接中,接受的答案在 C# 语言规范版本 3.0,第 240 页

foreach遍历的顺序
数组的元素,如下
如下:对于一维数组
元素以递增的方式被遍历
索引顺序,从索引 0 开始并且
以索引长度 – 1 结尾。对于
多维数组,元素为
遍历使得索引
最右边的尺寸增加
首先,然后是下一个左侧维度,
等等到左边。下列
示例打印出 a 中的每个值
二维数组,在元素中
订单:

使用系统;
班级测试
{
  静态无效主(){
      双[,]值= {
          {1.2, 2.3, 3.4, 4.5},
          {5.6, 6.7, 7.8, 8.9}
      };
      foreach(值中的双元素值)
          Console.Write("{0} ", elementValue);
      Console.WriteLine();
  }
}

产生的输出如下:
1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9 在示例中

int[] 数字 = { 1, 3, 5, 7, 9 };
foreach (var n 数字) Console.WriteLine(n);
n 的类型被推断为 int,即数字的元素类型。

In your link, the accepted answer states in C# Language Specification Version 3.0, page 240:

The order in which foreach traverses
the elements of an array, is as
follows: For single-dimensional arrays
elements are traversed in increasing
index order, starting with index 0 and
ending with index Length – 1. For
multi-dimensional arrays, elements are
traversed such that the indices of the
rightmost dimension are increased
first, then the next left dimension,
and so on to the left. The following
example prints out each value in a
two-dimensional array, in element
order:

using System;
class Test
{
  static void Main() {
      double[,] values = {
          {1.2, 2.3, 3.4, 4.5},
          {5.6, 6.7, 7.8, 8.9}
      };
      foreach (double elementValue in values)
          Console.Write("{0} ", elementValue);
      Console.WriteLine();
  }
}

The output produced is as follows:
1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9 In the example

int[] numbers = { 1, 3, 5, 7, 9 };
foreach (var n in numbers) Console.WriteLine(n);
the type of n is inferred to be int, the element type of numbers.
亢潮 2024-08-19 10:08:32

该顺序由用于使用 foreach 循环遍历数据集合的迭代器定义。

如果您使用的是可索引的标准集合(例如 List),那么它将从索引 0 开始向上遍历该集合。

如果您需要控制顺序,您可以控制 实现您自己的 IEnumerable,或者您可以在执行 foreach 循环之前按照您想要的方式对列表进行排序。

这解释了枚举器如何用于通用列表。起初,当前元素未定义,并使用 MoveNext 到达下一项。

如果您阅读 MoveNext ,则表明它将从第一个元素开始集合中的一个,然后从那里移动到下一个,直到到达集合的末尾。

The order is defined by the iterator being used to traverse a collection of data using a foreach loop.

If you are using a standard collection that is indexable (such as a List), then it will traverse the collection starting with index 0 and moving up.

If you need to control the ordering you can either control how the iteration of the collection is handled by implementing your own IEnumerable, or you can sort the list the way you want it before executing the foreach loop.

This explains how Enumerator works for generic List. At first the current element is undefined and uses MoveNext to get to the next item.

If you read MoveNext it indicates that it will start with the first element of the collection and from there move to the next one until it reaches the end of the collection.

宛菡 2024-08-19 10:08:32

我只需要做一些类似于快速破解代码的事情,尽管它对我想做的事情不起作用,但它确实为我重新排序了列表。

使用 LINQ 更改顺序

         DataGridViewColumn[] gridColumns = new DataGridViewColumn[dataGridView1.Columns.Count];
         dataGridView1.Columns.CopyTo(gridColumns, 0); //This created a list of columns

         gridColumns = (from n in gridColumns
                        orderby n.DisplayIndex descending
                        select n).ToArray(); //This then changed the order based on the displayindex

I've just had to do something similar as a quick hack of code, though it didn't work for what I was trying to do it did reorder the list for me.

Using LINQ to change the order

         DataGridViewColumn[] gridColumns = new DataGridViewColumn[dataGridView1.Columns.Count];
         dataGridView1.Columns.CopyTo(gridColumns, 0); //This created a list of columns

         gridColumns = (from n in gridColumns
                        orderby n.DisplayIndex descending
                        select n).ToArray(); //This then changed the order based on the displayindex
哆兒滾 2024-08-19 10:08:32

列表似乎按照项目在后备存储中的顺序返回项目——因此,如果它们以这种方式添加到列表中,它们也会以这种方式返回。

如果您的程序取决于顺序,您可能需要在遍历列表之前对其进行排序。

对于线性搜索来说,这有点愚蠢——但如果您需要以某种方式排序,那么最好的选择就是按该顺序排列项目。

Lists seem to return the items in an order they are in the backing store--so if they are added to the list that way they'll be returned that way.

If your program depends on the ordering, you may want to sort it before traversing the list.

It's somewhat silly for linear searches--but if you need the order a certain way your best bet is make the items in that order.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文