diff --git a/Leaf.Core/Extensions/CollectionExtensions.cs b/Leaf.Core/Extensions/CollectionExtensions.cs new file mode 100644 index 0000000..ccd1447 --- /dev/null +++ b/Leaf.Core/Extensions/CollectionExtensions.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; + +namespace Leaf.Core.Extensions +{ + public static class CollectionExtensions + { + /// + /// Получить следующий случайный элемент. + /// + /// Тип элементов в коллекции + /// Список с элементами + /// Вернет случайный элемент из коллекции. + public static T NextRandom(this IReadOnlyList list) + { + if (list.Equals(default(IReadOnlyList)) || list.Count == 0) + return default(T); + + return list[Randomizer.Instance.Next(0, list.Count)]; + } + } +} \ No newline at end of file diff --git a/Leaf.Core/Randomizer.cs b/Leaf.Core/Randomizer.cs new file mode 100644 index 0000000..549429b --- /dev/null +++ b/Leaf.Core/Randomizer.cs @@ -0,0 +1,13 @@ +using System; + +namespace Leaf.Core +{ + /// + /// Singleton for Random class. + /// + public static class Randomizer + { + [ThreadStatic] private static Random _rand; + public static Random Instance => _rand ?? (_rand = new Random()); + } +} \ No newline at end of file