首页 > 技术文章 > .net扩展方法——其他(科学计数法、ToDictionary 去重、List<Guid>转为List<Guid?>)

amusement1992 2020-08-13 14:13 原文

.net扩展方法——其他:

  1. ChangeToDecimal:数字科学计数法处理
  2. ToDictionaryEx:ToDictionary 去重
  3. ToListGuid:List<Guid>转为List<Guid?>

 

科学计数法的测试调用:

            string val = "7.8E+07";//7.8*10^7(10的7次方) 科学计数法的表示。例如1.03乘10的8次方,可简写为“1.03E+08”的形式
            var result = val.ChangeToDecimal();//结果:78000000M

 

扩展方法:

        /// <summary>
        /// 数字科学计数法处理
        /// </summary>
        /// <param name="strData"></param>
        /// <returns></returns>
        public static decimal ChangeToDecimal(this string strData)
        {
            decimal dData = 0.0M;
            if (strData.Contains("E"))
            {
                dData = Convert.ToDecimal(decimal.Parse(strData.ToString(), System.Globalization.NumberStyles.Float));
            }
            else
            {
                dData = Convert.ToDecimal(strData);
            }
            return Math.Round(dData, 4);
        }

        /// <summary>
        /// ToDictionary 去重
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="source"></param>
        /// <param name="keyGetter"></param>
        /// <param name="valueGetter"></param>
        /// <returns></returns>
        public static IDictionary<TKey, TValue> ToDictionaryEx<TElement, TKey, TValue>(
            this IEnumerable<TElement> source,
            Func<TElement, TKey> keyGetter,
            Func<TElement, TValue> valueGetter)
        {
            IDictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
            foreach (var e in source)
            {
                var key = keyGetter(e);
                if (dict.ContainsKey(key))
                {
                    continue;
                }

                dict.Add(key, valueGetter(e));
            }
            return dict;
        }

        /// <summary>
        /// List<Guid?>转为List<Guid>
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static List<Guid> ToListGuid(this List<Guid?> val)
        {
            return val.Select(x => x ?? Guid.Empty).ToList();
        }

        /// <summary>
        /// List<Guid>转为List<Guid?>
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static List<Guid?> ToListGuid(this List<Guid> val)
        {
            return val.Select(x => new Guid?(x)).ToList();
        }

 

推荐阅读