Is there a way to use a foreach loop to iterate through a collection backwards or in a completely random order?
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);