0

I have a list that can have a variable amount of items (but no more than ~30 so no performance issue here), I want to get maximum 10 random items and I wrote a piece of code for that which works fine if there are 10+ items in the list. The issue with the code below is that it obviously doesn't randomize the result if there are less than 10 items in the list and if there are less than 10 items I want to display them all but in random order.

var keyPersons = people.ToList();
Random rnd = new Random();
while (keyPersons.Count() > 10)
{
    int j = rnd.Next(0, keyPersons.Count());
    keyPersons.RemoveAt(j);
}

rptKeyPersons.DataSource = keyPersons;

How can I randomize the result if there are let's say only five items in the person list?

Thanks in advance.

user997685
  • 543
  • 2
  • 7
  • 14
  • 2
    Your code will remove items at random points until there are exactly 10 items left. If you have less than 10 items, you'll simply end up with whatever the list already was. So what's the issue? Do you need a random *ordering*? In either case, I might just shuffle the list and take the first 10 items, obviously allowing that less than 10 might be present, which sounds fine according to your rules. – Anthony Pegram Feb 13 '12 at 04:24
  • yeah sorry I updated the question a bit, if there are less than 10 I want them all but in a random order. – user997685 Feb 13 '12 at 04:25
  • for shuffling a list: http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp – mshsayem Feb 13 '12 at 04:30

2 Answers2

4

Given the clarification in the comments that you need a randomized ordering, you can perform a shuffle of the list and then simply take n items in order. Note that even when your list had more than 10 items, your method still not cover randomizing those results beyond eliminating elements at random points. The elements left were still in their original order otherwise. This will address both issues.

Given

public static void Shuffle<T>(IList<T> list)
{
    var random = new Random();
    for (int index = list.Count - 1; index >= 1; index--)
    {
        int other = random.Next(0, index + 1);
        T temp = list[index];
        list[index] = list[other];
        list[other] = temp;
    }
}

You could have

var keyPersons = people.ToList();  
Shuffle(keyPersons);  
rptKeyPersons.DataSource = keyPersons.Take(10);

Take would select the first 10 items in the freshly shuffled sequence. If less than 10 exist, it simply takes as many as are available.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
0

I like Anthonies solution but it can be as simple as this.

var keyPersons = people.OrderBy(x => Guid.NewId()).ToList()
rptKeyPersons.DataSource = keyPersons.Take(10);
Community
  • 1
  • 1
shenku
  • 11,969
  • 12
  • 64
  • 118