56

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?

Edit: Found it here: How to get a Random Object using Linq

PassionateDeveloper
  • 14,558
  • 34
  • 107
  • 176

8 Answers8

80

Like this:

var rand = new Random();
var user = users[rand.Next(users.Count)];
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 19
    Note: In real code `var rand = new Random();` should be initialized somewhere else so that it will only be seeded once. If this code is called multiple times in quick succession, the new instances of `Random` may end up using the same seed and thus returning the same value when calling `Next`. – Brian Jan 06 '11 at 19:17
  • 4
    Indeed, this rand could be `static` – Junior Mayhé May 04 '17 at 20:27
  • I belive users collection is zero base so it should be like: var user = users[rand.Next(users.Count-1)]; – Roman Feb 22 '19 at 08:36
  • 1
    @Roman Count -1 isn't needed, `rand.Next` "Returns a non-negative random integer that is **less** than the specified maximum" – 4imble Nov 12 '19 at 14:10
37

Use ElementAt:

var rand = new Random();
var user = users.ElementAt( rand.Next( users.Count() ) );
Danko Durbić
  • 7,077
  • 5
  • 34
  • 39
16

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();
longda
  • 10,153
  • 7
  • 46
  • 66
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
Cihan Yakar
  • 2,402
  • 28
  • 30
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();
ilivewithian
  • 19,476
  • 19
  • 103
  • 165
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.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
2
list.OrderBy(x=> Guid.NewGuid()).Take(10)
TheKido
  • 99
  • 3
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);
CJ Edgerton
  • 400
  • 3
  • 11