Extensions.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using Masuit.Tools.RandomSelector;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace Masuit.Tools
  6. {
  7. public static partial class Extensions
  8. {
  9. public static int TotalWeight<T>(this WeightedSelector<T> selector)
  10. {
  11. return selector.Items.Count == 0 ? 0 : selector.Items.Sum(t => t.Weight);
  12. }
  13. public static List<WeightedItem<T>> OrderByWeightDescending<T>(this WeightedSelector<T> selector)
  14. {
  15. return selector.Items.OrderByDescending(item => item.Weight).ToList();
  16. }
  17. public static List<WeightedItem<T>> OrderByWeightAscending<T>(this WeightedSelector<T> selector)
  18. {
  19. return selector.Items.OrderBy(item => item.Weight).ToList();
  20. }
  21. public static T WeightedItem<T>(this IEnumerable<WeightedItem<T>> list)
  22. {
  23. return new WeightedSelector<T>(list).Select();
  24. }
  25. public static IEnumerable<T> WeightedItems<T>(this IEnumerable<WeightedItem<T>> list, int count)
  26. {
  27. return new WeightedSelector<T>(list).SelectMultiple(count);
  28. }
  29. /// <summary>
  30. /// 执行权重筛选,取多个元素
  31. /// </summary>
  32. /// <typeparam name="T"></typeparam>
  33. /// <param name="source">原始数据</param>
  34. /// <param name="count">目标个数</param>
  35. /// <param name="keySelector">按哪个属性进行权重筛选</param>
  36. /// <param name="option">抽取选项</param>
  37. /// <returns></returns>
  38. public static IEnumerable<T> WeightedItems<T>(this IEnumerable<T> source, int count, Func<T, int> keySelector, SelectorOption option = null)
  39. {
  40. var items = source as IList<T> ?? source.ToList();
  41. if (!items.Any())
  42. {
  43. return items;
  44. }
  45. var selector = new WeightedSelector<T>(items.Select(t => new WeightedItem<T>(t, keySelector(t))), option);
  46. return selector.SelectMultiple(count);
  47. }
  48. /// <summary>
  49. /// 执行权重筛选,取1个元素
  50. /// </summary>
  51. /// <typeparam name="T"></typeparam>
  52. /// <param name="source">原始数据</param>
  53. /// <param name="keySelector">按哪个属性进行权重筛选</param>
  54. /// <param name="option">抽取选项</param>
  55. /// <returns></returns>
  56. public static T WeightedBy<T>(this IEnumerable<T> source, Func<T, int> keySelector, SelectorOption option = null)
  57. {
  58. var selector = new WeightedSelector<T>(source.Select(t => new WeightedItem<T>(t, keySelector(t))), option);
  59. return selector.Select();
  60. }
  61. }
  62. }