mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-04-13 20:47:24 +00:00
feat: Extension method for getting a random item from a sequence
This commit is contained in:
parent
5f7d1214e9
commit
fa145644d1
1 changed files with 22 additions and 0 deletions
|
|
@ -851,6 +851,28 @@ namespace ICD.Common.Utils.Extensions
|
||||||
return extends.Distinct(new PredicateEqualityComparer<TItem, TProperty>(propertyComparer, getProperty));
|
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>
|
/// <summary>
|
||||||
/// Returns other if the sequence is empty.
|
/// Returns other if the sequence is empty.
|
||||||
/// Returns other if the sequence is non-empty and there are two different elements.
|
/// Returns other if the sequence is non-empty and there are two different elements.
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue