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

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

    Using an IList from the C5 Generic Collection Library, Reverse iteration is a feature, rather than extension:

    foreach (var i in list.Reverse())
    {
    }
    

    As well, you can use the Shuffle() method to get a random ordering:

    var listClone = (IList) list.Clone();
    listClone.Shuffle();
    foreach (var i in listClone)
    {
    }
    

提交回复
热议问题