In what order does a C# for each loop iterate over a List?

前端 未结 6 1224
南旧
南旧 2020-12-03 00:35

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

I found another question abou

6条回答
  •  时光说笑
    2020-12-03 00:51

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

    internal Enumerator(List list) {
        this.list = list;
        index = 0;
        version = list._version;
        current = default(T);
    }
    
    public bool MoveNext() {
    
        List 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

提交回复
热议问题