mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-02-06 16:25:04 +00:00
feat: Extension method for getting a random item from a sequence
This commit is contained in:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user