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?
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?
Like this:
var rand = new Random();
var user = users[rand.Next(users.Count)];
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();
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.