MultipleSelector.cs 1.5 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 List<T> Select(int count)
  15. {
  16. Validate(ref count);
  17. var items = new List<WeightedItem<T>>(WeightedSelector.Items);
  18. var resultList = new List<T>();
  19. do
  20. {
  21. var item = WeightedSelector.Option.AllowDuplicate ? BinarySelect(items) : LinearSelect(items);
  22. resultList.Add(item.Value);
  23. if (!WeightedSelector.Option.AllowDuplicate)
  24. {
  25. items.Remove(item);
  26. }
  27. } while (resultList.Count < count);
  28. return resultList;
  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. throw new InvalidOperationException("没有元素可以被筛选");
  40. }
  41. if (!WeightedSelector.Option.AllowDuplicate && items.Count < count)
  42. {
  43. count = items.Count;
  44. }
  45. }
  46. }
  47. }