Is there a way to use a foreach
loop to iterate through a collection backwards or in a completely random order?
An array is a collection of objects, each of which is of the same type. Items in an array are called elements.
A collection is a class, so you must declare an instance of the class before you can add elements to that collection. If your collection contains elements of only one data type, you can use one of the classes in the System. Collections. Generic namespace.
To return a collection with repeated elements in C#, use Enumerable. Repeat method. It is part of System. Linq namespace.
Using System.Linq
you could do...
// List<...> list;
foreach (var i in list.Reverse())
{
}
For a random order you'd have to sort it randomly using list.OrderBy
(another Linq extension) and then iterate that ordered list.
var rnd = new Random();
var randomlyOrdered = list.OrderBy(i => rnd.Next());
foreach (var i in randomlyOrdered)
{
}
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<T> OrderRandomly<T>(this IEnumerable<T> sequence)
{
Random random = new Random();
List<T> 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With