From 07ddb5537471632806e23cbd8c56f60908b30b98 Mon Sep 17 00:00:00 2001 From: grandsilence Date: Tue, 4 Dec 2018 16:19:29 +0300 Subject: [PATCH] Added Randomizer and extension for all collections "NextRandom". --- Leaf.Core/Extensions/CollectionExtensions.cs | 21 ++++++++++++++++++++ Leaf.Core/Randomizer.cs | 13 ++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 Leaf.Core/Extensions/CollectionExtensions.cs create mode 100644 Leaf.Core/Randomizer.cs 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