EnumerableExt.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Quadarax.Foundation.Core.Value.Extensions
  5. {
  6. public static class EnumerableExt
  7. {
  8. private static Random _rand = new Random();
  9. private const string CS_MESSAGE_MUST_HAVE_ONE = "Collection must have at least one element.";
  10. private const string CS_MESSAGE_MUST_POSITIVE = "Must be positive number.";
  11. private const string CS_MESSAGE_MUST_SMALLER = "fromIndex must be smaller or equal to toIndex.";
  12. public static TElement GetRandom<TElement>(this IEnumerable<TElement> owner)
  13. {
  14. if (owner == null)
  15. throw new ArgumentNullException(nameof(owner));
  16. if (!owner.Any())
  17. throw new ArgumentOutOfRangeException(nameof(owner), CS_MESSAGE_MUST_HAVE_ONE);
  18. return GetRandom(owner, 0, owner.Count());
  19. }
  20. public static TElement GetRandom<TElement>(this IEnumerable<TElement> owner, int fromIndex, int toIndex = -1)
  21. {
  22. if (owner == null)
  23. throw new ArgumentNullException(nameof(owner));
  24. if (!owner.Any())
  25. throw new ArgumentOutOfRangeException(nameof(owner), CS_MESSAGE_MUST_HAVE_ONE);
  26. if (toIndex == -1)
  27. toIndex = owner.Count() - 1;
  28. if (fromIndex<0)
  29. throw new ArgumentOutOfRangeException(nameof(fromIndex), CS_MESSAGE_MUST_POSITIVE);
  30. if (toIndex<0)
  31. throw new ArgumentOutOfRangeException(nameof(fromIndex), CS_MESSAGE_MUST_POSITIVE);
  32. if (fromIndex>toIndex)
  33. throw new ArgumentOutOfRangeException(nameof(fromIndex), CS_MESSAGE_MUST_SMALLER);
  34. var index = _rand.Next(fromIndex, toIndex);
  35. return owner.Skip(index).Take(1).First();
  36. }
  37. }
  38. }