0

I have a list of object which contain all user information.

List<UsrProfile> listUsr = GetAllUser();

In dashboard I have to show only 10 user profile randomly from list on each page refresh.

tereško
  • 58,060
  • 25
  • 98
  • 150
developer
  • 25
  • 6

4 Answers4

3

I prefer using LINQ, short and more readable.

var r = new Random(); 
var tenRandomUser = listUsr.OrderBy(u => r.Next()).Take(10);
I Putu Yoga Permana
  • 3,980
  • 29
  • 33
  • This works, but be careful. If you call it many times in succession (for example, in a tight loop), you'll likely find that you get the same numbers multiple times because the random number generator is initialized with the same seed. Better off to create a persistent `Random` instance in the constructor, and then use it each time the method to get random items is called. – Jim Mischel Jan 04 '16 at 18:04
  • yes, maybe static instance of `Random` will help – I Putu Yoga Permana Jan 05 '16 at 04:45
1

You can do it in two ways (ok, maybe more, but two comes to mind). One is as @wentimo described. Second is to create resulting list and randomly choose from source list and add in resulting if it's not already there:

This should do what you're after: It creates a temporary list to make sure you don't randomly choose a duplicate you've already chosen and also assumes the list has at least 10 elements.

Random rnd = new Random();
List<User> resultList = new List<User>();

while (resultList.Count < 10)
{
    User u = listUsr[rnd.Next(listUsr.Count)];
    if (!resultList.Contains(u))
    {
        resultList.Add(u);
    }
}

When you should use which way? If number of random elements is far less than number of elements in source list, use second approach. For example, if you are choosing 10 out of 100,000 users, you will rarely get same user twice and checking if resulting list contains element is fast for small number of elements.

On the other side, you are avoiding creating one more list of 100,000 elements. If number of random elements is close to number of source elements, then use first approach because you would often pick two or more times same user and resultList would check existence over larger number of elements.

Also, if not sure about relation between number of source elements and number of random elements you want to take, choose first (@wentimo's) solution.

Shadowed
  • 956
  • 7
  • 19
0

This should do what you're after: It creates a temporary list to make sure you don't randomly choose a duplicate you've already chosen and also assumes the list has at least 10 elements.

Random rnd = new Random();

var tempList = new List<User>(listUsr);

int count = 10;

while (count > 0)
{
    int r = rnd.Next(tempList.Count);
    // Do whatever with tempList[r] 
    templist.RemoveAt(r);
    count--;
}
wentimo
  • 471
  • 3
  • 12
-1

You can use the below line of code -

listUsr.Take(10);

Nikita
  • 75
  • 4