Random element of List<T> from LINQ SQL
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
Solution 1:
Like this:
var rand = new Random();
var user = users[rand.Next(users.Count)];
Solution 2:
Use ElementAt
:
var rand = new Random();
var user = users.ElementAt( rand.Next( users.Count() ) );
Solution 3:
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();