Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get X random elements from table in database using Linq or lambda in C#

Tags:

c#

linq

I have a database with x amount users and I want to randomly get all the users and then write like 50 users out on my site. Right now I'm only using .take(50) and retrieves the latest 50 users. I want it to shuffle 50 random from whole table, Any ideas?

This is what my code looks like now:

userList = userList.OrderBy(user => -user.ID).Take(userCount).ToList();

NOTE: userlist is my list of all users. and as you can see I'm at the moment using lambda with a variable called userCount where I say how many users to list out!

like image 943
user2862542 Avatar asked Oct 16 '13 08:10

user2862542


Video Answer


1 Answers

Try this

Random rnd = new Random();
userList = userList.OrderBy(user => rnd.Next()).Take(usercount).ToList();
like image 175
MikeSW Avatar answered Oct 24 '22 19:10

MikeSW