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

前端 未结 5 2035
轻奢々
轻奢々 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 15:02

    There are 2 ways of doing this depending on how many users are in your system

    1.

    List ids = new List(50);
    int total = userList.Count();
    Random r = new Random();
    while (ids.Count() < 50)
    {
        var next = r.Next(total);
        if (!ids.Contains(next))
            ids.Add(next);
    }
    var users = userList.Where(a => ids.Contains(a.ID));
    

    2.

    MikeSW beat me to that one

    Difference between the options is that 1) involves 2 queries queries to the database and 2) involves loading all of the users from the database just to load 50 of them. It's up to you which is a better way of doing it.

提交回复
热议问题