1

I have the following piece of code:

    private Random r = new Random();

    private List<T> RandomElement<T>(IQueryable<T> list, Expression<Func<T, bool>> e, int items = 3)
    {
        list = list.Where(e);
        return list.Skip(r.Next(list.Count())).Take(items).ToList();
    }    

The problem is when I call it and want for example to return 3 random items from a list, sometimes returns 3 sometimes 2, sometimes 1 ?

I want at all time to get 3.

What I am doing wrong?

user2818430
  • 5,853
  • 21
  • 82
  • 148
  • As the name suggests, *Skip* skips n elements which means it may skip all elements in your list :) Have you read about `fisher yates shuffle`? If not, Google it and read the first result. – Eser Aug 16 '15 at 19:35
  • Thanks for the info. Actually never heard of it but I will give it a read. – user2818430 Aug 16 '15 at 19:48

1 Answers1

0

If you have 10 elements in your list, and you ask for 3 "random" items, in your solution if the random number generator returns 8, you skip the first 8 elements and it only has 2 items available to return (items 9 and 10). That is why it is happening.

If you want random items, instead shuffle the list and do not skip any, just take the number you want.

Randomize a List<T>

Community
  • 1
  • 1
viggity
  • 15,039
  • 7
  • 88
  • 96
  • 1
    `If you want random items, instead shuffle the list`, Funny that accepted answer uses *fisher yates shuffle* in your link – Eser Aug 16 '15 at 19:58