Random element of List from LINQ SQL

2019-01-23 10:30发布

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 user from that list. What's the best way to go about doing that?

6条回答
在下西门庆
2楼-- · 2019-01-23 10:59

Use ElementAt:

var rand = new Random();
var user = users.ElementAt( rand.Next( users.Count() ) );
查看更多
老娘就宠你
3楼-- · 2019-01-23 11:03

How about something like this?

var users = GetUsers();
var count = user.Count();
var rand = new System.Random();
var randomUser = users.Skip(rand.Next(count)).FirstOrDefault();
查看更多
女痞
4楼-- · 2019-01-23 11:07

Like this:

var rand = new Random();
var user = users[rand.Next(users.Count)];
查看更多
迷人小祖宗
5楼-- · 2019-01-23 11:19

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.

查看更多
干净又极端
6楼-- · 2019-01-23 11:23

Why not create a generic helper and/or extension?!

namespace My.Core.Extensions
{
    public static class EnumerableHelper<E>
    {
        private static Random r;

        static EnumerableHelper()
        {
            r = new Random();
        }

        public static T Random<T>(IEnumerable<T> input)
        {
            return input.ElementAt(r.Next(input.Count()));
        }

    }

    public static class EnumerableExtensions
    {
        public static T Random<T>(this IEnumerable<T> input)
        {
            return EnumerableHelper<T>.Random(input);
        }
    }
}

Usage would be:

        var list = new List<int>() { 1, 2, 3, 4, 5 };

        var output = list.Random();
查看更多
7楼-- · 2019-01-23 11:23

for Entity Framework or Linq 2 Sql, can use this extension method

public static T RandomElement<T>(this IQueryable<T> q, Expression<Func<T,bool>> e)
{
   var r = new Random();
   q  = q.Where(e);
   return q.Skip(r.Next(q.Count())).FirstOrDefault();
}
// persons.RandomElement(p=>p.Age > 18) return a random person who +18 years old
// persons.RandomElement(p=>true) return random person, you can write an overloaded version with no expression parameter
查看更多
登录 后发表回答