Can you enumerate a collection in C# out of order?

前端 未结 11 2129
天涯浪人
天涯浪人 2020-12-17 17:15

Is there a way to use a foreach loop to iterate through a collection backwards or in a completely random order?

11条回答
  •  余生分开走
    2020-12-17 17:52

    you can do it backwards:

    for (int i=col.count-1; i>0; i--){ 
          DoSomething ( col.item[i]) ;
    }
    

    Not certain about the exact syntax, but that's the paradigm.

    As for completely random order, you can access a collection element via it's index. To ensure you hit every item, you would need to keep track of which elements you had already processed (probably by copying the collection and then removing the element after access).

    EDIT: More details for random access The code for the random access could look something like this:

     collection c = originalCollection;
     while (c.count > 0) {
         int i = randomNumber(seed) mod c.count
         element d = c[i];
         c.remove(d);
         DoSomething(d);
    }
    

提交回复
热议问题