user2862542 user2862542 - 6 months ago 37
C# Question

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

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

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();

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!


Try this

Random rnd = new Random();
userList = userList.OrderBy(user => rnd.Next()).Take(usercount).ToList();