Skip to content

Instantly share code, notes, and snippets.

@sapher
Created June 9, 2013 15:16
Show Gist options
  • Save sapher/5743892 to your computer and use it in GitHub Desktop.
Save sapher/5743892 to your computer and use it in GitHub Desktop.
Extension for IEnumerable that help to get one item randomly from a collection
using System;
using System.Collections.Generic;
using System.Linq;
namespace List.Extensions
{
public static class ListExtension
{
public static Object GetOneRandom<T>(this IEnumerable<T> list)
{
if (!list.Any()) throw new ArgumentNullException();
var random = new Random();
var enumerable = list as IList<T> ?? list.ToList();
return enumerable[random.Next(enumerable.Count)];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment