Random element of List<T> from LINQ SQL
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();