Random Element of List from Linq Sql [Duplicate]

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

0

Like this:

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

Use ElementAt:

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

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

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

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

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);
list.OrderBy(x=> Guid.NewGuid()).Take(10)
1
David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest