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

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

    Extension Without Random

    public static class MyExtensions
    {
        public static IEnumerable GetRandomItems(this IEnumerable source, Int32 count)
        {
            return source.OrderBy(s => Guid.NewGuid()).Take(count);
        }
    }
    

    And now you can

    userList = userList.GetRandomItems().ToList();
    

提交回复
热议问题