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

前端 未结 11 2096
天涯浪人
天涯浪人 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:54

    I actually liked cfeduke approach with LINQ and it bugs me that it slipped my mind. To add to my previous example. If you want to do the Odd and Even iterations with the help of LINQ you can use

    // Even
    foreach (var i in ints.FindAll(number => number % 2 == 0))
    {
          Console.WriteLine(i);
    }
    
    // Odd
    foreach (var i in ints.FindAll(number => number % 2 != 0))
    {
          Console.WriteLine(i);
    }
    

提交回复
热议问题