Random element of List from LINQ SQL

前端 未结 6 1259
执笔经年
执笔经年 2020-12-15 02:35

I\'m using C# 3.5 and am currently using Linq to get all users from a user table and put them in a list.

Now I would like to return a random

6条回答
  •  执念已碎
    2020-12-15 03:23

    The Random class can be used to generate pseudo-random numbers. Use it to generate a random number within the range of valid indices into your array or list.

    Random rand = new Random();
    var user = Users[rand.Next(Users.Count)];
    

    If you want to see more examples, I created several random-oriented LINQ extensions and published it in the article Extending LINQ with Random Operations.

提交回复
热议问题