Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

loops

foreach

Is there a way to use a foreach loop to iterate through a collection backwards or in a completely random order?

like image 689
Jason Z Avatar asked Oct 31 '08 19:10

Jason Z


People also ask

Is array a collection in C#?

An array is a collection of objects, each of which is of the same type. Items in an array are called elements.

What is collection in C sharp?

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.

How do I return a collection in C#?

To return a collection with repeated elements in C#, use Enumerable. Repeat method. It is part of System. Linq namespace.


2 Answers

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)
{
}
like image 94
cfeduke Avatar answered Oct 02 '22 14:10

cfeduke


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);
like image 36
Jacob Carpenter Avatar answered Oct 02 '22 15:10

Jacob Carpenter