feat: Extension method for getting a random item from a sequence

This commit is contained in:
Chris Cameron
2018-07-25 11:59:00 -04:00
parent 5f7d1214e9
commit fa145644d1

View File

@@ -851,6 +851,28 @@ namespace ICD.Common.Utils.Extensions
return extends.Distinct(new PredicateEqualityComparer<TItem, TProperty>(propertyComparer, getProperty));
}
/// <summary>
/// Returns a random item from the given sequence.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <returns></returns>
public static T Random<T>(this IEnumerable<T> extends)
{
if (extends == null)
throw new ArgumentNullException("extends");
IList<T> sequence = extends as IList<T> ?? extends.ToArray();
if (sequence.Count == 0)
throw new InvalidOperationException("Sequence is empty.");
Random random = new Random(Guid.NewGuid().GetHashCode());
int index = random.Next(0, sequence.Count);
return sequence[index];
}
/// <summary>
/// Returns other if the sequence is empty.
/// Returns other if the sequence is non-empty and there are two different elements.