Skip to content

Commit

Permalink
Added Randomizer and extension for all collections "NextRandom".
Browse files Browse the repository at this point in the history
  • Loading branch information
grandsilence committed Dec 4, 2018
1 parent bbe6335 commit 07ddb55
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
21 changes: 21 additions & 0 deletions Leaf.Core/Extensions/CollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Collections.Generic;

namespace Leaf.Core.Extensions
{
public static class CollectionExtensions
{
/// <summary>
/// Получить следующий случайный элемент.
/// </summary>
/// <typeparam name="T">Тип элементов в коллекции</typeparam>
/// <param name="list">Список с элементами</param>
/// <returns>Вернет случайный элемент из коллекции.</returns>
public static T NextRandom<T>(this IReadOnlyList<T> list)
{
if (list.Equals(default(IReadOnlyList<T>)) || list.Count == 0)
return default(T);

return list[Randomizer.Instance.Next(0, list.Count)];
}
}
}
13 changes: 13 additions & 0 deletions Leaf.Core/Randomizer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;

namespace Leaf.Core
{
/// <summary>
/// Singleton for Random class.
/// </summary>
public static class Randomizer
{
[ThreadStatic] private static Random _rand;
public static Random Instance => _rand ?? (_rand = new Random());
}
}

0 comments on commit 07ddb55

Please sign in to comment.