Created
June 9, 2013 15:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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