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

前端 未结 5 2050
轻奢々
轻奢々 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:06

    Assuming you have an Id primary key column in your entity I would recommend to use the following query or you will be bringing down a lot of data for no reason.

    var rnd = new Random();
    
    // Get the employeeIds.
    var employeeIds = EmployeeService.Data()
        .Select(e => e.Id)
        .ToList();
    
    // Choose n number of random employeeIds.
    var randomEmployeeIds = employeeIds
        .OrderBy(id => rnd.Next())
        .Take(x);
    
    // Get random employees.
    var employees = EmployeeService.Data().Where(emp => randomEmployeeIds.Contains(emp.Id));
    

提交回复
热议问题