score:79

Accepted answer

Like this:

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

score:0

Not exactly applicable in all cases but below is an alternative solution that I found handy since I was already using Bogus in my project.

List<User> myUserList = _context.Users.ToList();

var _faker = new Faker("en");
User randomUser = _faker.Random.ListItem<User>(myUserList);

score:2

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.

score:3

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();

score:10

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

score:14

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();

score:36

Use ElementAt:

var rand = new Random();
var user = users.ElementAt( rand.Next( users.Count() ) );

Related Query

More Query from same tag