MultipleSelector.cs 1.3 KB

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