Rati_Ge
Rati_Ge

Reputation: 1270

Access all items inside List<T> in a random order

I have a List where T has a property CoverImage. I want to access all items inside the list in a random order and load the appropriate image from server. I am not interested in loading data from server, all I want to know is how to access all the elements inside that list in a random way and only once?

Upvotes: 0

Views: 213

Answers (4)

itsme86
itsme86

Reputation: 19496

If you're interested in writing your own extension method, it might look like this:

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> enumerable, Random random)
{
    List<T> itemList = new List<T>(enumerable);

    for (int i = 0; i < itemList.Count; ++i)
    {
        int randomIndex = random.Next(itemList.Count);
        if (randomIndex != i)
        {
            T temp = itemList[i];
            itemList[i] = itemList[randomIndex];
            itemList[randomIndex] = temp;
        }
    }

    return itemList;
}

Upvotes: 0

Jose Alonso
Jose Alonso

Reputation: 31

Random r = new Random();
List<T> myListRnd = new List<T>();

int p = 0;
while (myList.Count > 0)
{
    p = r.Next(myList.Count + 1)
    myListRnd.Add(myList[p]);
    myList.RemoveAt[p];
}

Upvotes: 0

Servy
Servy

Reputation: 203835

The appropriate term for this is shuffling. Shuffling is the concept of re-ordering a collection/sequence into a random order.

There are many means of doing so, with varying performance implications. A great choice is the Fisher–Yates shuffle

The pseudocode:

To shuffle an array a of n elements (indices 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]

Upvotes: 2

I4V
I4V

Reputation: 35353

Random rnd = new Random();
foreach(var elem in list.OrderBy(x => rnd.Next()))
{

}

Upvotes: 4

Related Questions