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

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

    I don't think there is a way to do so directly, but it's pretty much as good to use an extension method that returns a new collection via the yield return keyword. These could come from a pre-existing library; the others have pointed out that LINQ has a Reverse method, and things like OrderBy would also work.

    Example: if you use the LINQ extension method Reverse() on IEnumerable, which uses yield return to give the collection in reverse order, then doing a foreach(var myThing in myCollection.Reverse()) will enumerate through the collection in reverse order.

    Important: yield return is key. It means "when I enumerate this collection, then go fetch things." As opposed to the alternative of just constructing a new, reversed collection, which is highly inefficient and possibly has side effects.

提交回复
热议问题