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

前端 未结 5 2006
轻奢々
轻奢々 2021-01-11 14:22

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)

5条回答
  •  花落未央
    2021-01-11 14:59

    When it is okay to load all users and then take 50 of them, you can use a while loop like this:

    List randomUsers = new List();
    Random r = new Random();
    while (randomUsers.Count < 50)
    {
        userList
          // skip previously selected users
          .Except(randomUsers)
          // random number to skip a random amount of users
          .Skip(r.Next(0, userList.Count() - 1 - randomUsers.Count))
          // and then take the next one
          .First();
    }
    
        

    提交回复
    热议问题