C# 广告权重算法,

 


    /// <summary>
    /// 权重运算
    /// </summary>
    public static class WeightsOper<T>
    {
        /// <summary>
        /// 根据权重随机抽取一个实体
        /// </summary>
        /// <param name="obj">实体列表</param>
        /// <returns>返回被抽取的实体</returns>
        public static object GetWeight(IList<T> obj)
        {
            var list = GenerateWeightList(obj);
            int ranNum = RandomNumber(list.Count - 1);
            var result = list[ranNum];
            return result;
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private static int RandomNumber(int length)
        {
            Random rad = new Random();
            return rad.Next(0, length);
        }

        /// <summary>
        /// 生成权重序列表
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <returns>返回数据列表</returns>
        private static IList<T> GenerateWeightList(IList<T> data)
        {          
           int weight = 0;       
           IList<T> list = new List<T>();
           foreach (var one in data)
           {
                Type type = typeof(T);
                var t = type.GetProperties();
                int vweight = 0;
                // Weight 为权重数 只支持整数
                if (int.TryParse(type.GetProperty("Weight").GetValue(one, null).ToString(), out vweight))
                {
                    weight += vweight;
                    for (int i = 0; i < vweight; i++)
                    {
                        list.Add(one);
                    }
                }
            }
            return list;
        }

    }

阅读更多
个人分类: WebFrom编程(ASP.NET)
下一篇C# 动态绑定实体数据
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭