using Masuit.Tools.RandomSelector; using System; using System.Collections.Generic; using System.Linq; namespace Masuit.Tools { public static partial class Extensions { public static int TotalWeight(this WeightedSelector selector) { return selector.Items.Count == 0 ? 0 : selector.Items.Sum(t => t.Weight); } public static List> OrderByWeightDescending(this WeightedSelector selector) { return selector.Items.OrderByDescending(item => item.Weight).ToList(); } public static List> OrderByWeightAscending(this WeightedSelector selector) { return selector.Items.OrderBy(item => item.Weight).ToList(); } public static T WeightedItem(this IEnumerable> list) { return new WeightedSelector(list).Select(); } public static IEnumerable WeightedItems(this IEnumerable> list, int count) { return new WeightedSelector(list).SelectMultiple(count); } /// /// 执行权重筛选,取多个元素 /// /// /// 原始数据 /// 目标个数 /// 按哪个属性进行权重筛选 /// 抽取选项 /// public static IEnumerable WeightedItems(this IEnumerable source, int count, Func keySelector, SelectorOption option = null) { var items = source as IList ?? source.ToList(); if (!items.Any()) { return items; } var selector = new WeightedSelector(items.Select(t => new WeightedItem(t, keySelector(t))), option); return selector.SelectMultiple(count); } /// /// 执行权重筛选,取1个元素 /// /// /// 原始数据 /// 按哪个属性进行权重筛选 /// 抽取选项 /// public static T WeightedBy(this IEnumerable source, Func keySelector, SelectorOption option = null) { var selector = new WeightedSelector(source.Select(t => new WeightedItem(t, keySelector(t))), option); return selector.Select(); } } }