Random element of List<T> from LINQ SQL

C#.NetLinqRandom

C# Problem Overview


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: http://stackoverflow.com/questions/3173718/linq-how-to-get-a-random-object-using-linq

C# Solutions


Solution 1 - C#

Like this:

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

Solution 2 - C#

Use ElementAt:

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

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.

Solution 7 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPassionateDeveloperView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#Danko DurbićView Answer on Stackoverflow
Solution 3 - C#longdaView Answer on Stackoverflow
Solution 4 - C#Cihan YakarView Answer on Stackoverflow
Solution 5 - C#ilivewithianView Answer on Stackoverflow
Solution 6 - C#Jonathan WoodView Answer on Stackoverflow
Solution 7 - C#CJ EdgertonView Answer on Stackoverflow