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.
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.
I prefer using LINQ, short and more readable.
var r = new Random();
var tenRandomUser = listUsr.OrderBy(u => r.Next()).Take(10);
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.
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--;
}