MultipleSelector.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Masuit.Tools.RandomSelector
  4. {
  5. /// <summary>
  6. /// 多选器
  7. /// </summary>
  8. /// <typeparam name="T"></typeparam>
  9. internal class MultipleSelector<T> : SelectorBase<T>
  10. {
  11. internal MultipleSelector(WeightedSelector<T> weightedSelector) : base(weightedSelector)
  12. {
  13. }
  14. internal IEnumerable<T> Select(int count)
  15. {
  16. Validate(ref count);
  17. var items = new List<WeightedItem<T>>(WeightedSelector.Items);
  18. int result = 0;
  19. do
  20. {
  21. var item = WeightedSelector.Option.AllowDuplicate ? BinarySelect(items) : LinearSelect(items);
  22. yield return item.Value;
  23. result++;
  24. if (!WeightedSelector.Option.AllowDuplicate)
  25. {
  26. items.Remove(item);
  27. }
  28. } while (result < count);
  29. }
  30. private void Validate(ref int count)
  31. {
  32. if (count <= 0)
  33. {
  34. throw new InvalidOperationException("筛选个数必须大于0");
  35. }
  36. var items = WeightedSelector.Items;
  37. if (items.Count == 0)
  38. {
  39. count = 0;
  40. return;
  41. }
  42. if (!WeightedSelector.Option.AllowDuplicate && items.Count < count)
  43. {
  44. count = items.Count;
  45. }
  46. }
  47. }
  48. }