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

前端 未结 11 2110
天涯浪人
天涯浪人 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 18:09

    As other answers mention, the Reverse() extension method will let you enumerate a sequence in reverse order.

    Here's a random enumeration extension method:

    public static IEnumerable OrderRandomly(this IEnumerable sequence)
    {
        Random random = new Random();
        List copy = sequence.ToList();
    
        while (copy.Count > 0)
        {
            int index = random.Next(copy.Count);
            yield return copy[index];
            copy.RemoveAt(index);
        }
    }
    

    Your usage would be:

    foreach (int n in Enumerable.Range(1, 10).OrderRandomly())
        Console.WriteLine(n);
    

提交回复
热议问题