1. 程式人生 > 實用技巧 >.net擴充套件方法——其他(科學計數法、ToDictionary 去重、List<Guid>轉為List<Guid?>)

.net擴充套件方法——其他(科學計數法、ToDictionary 去重、List<Guid>轉為List<Guid?>)

.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(); }