記錄下在開發中經常用到的類型轉換 /// <summary> /// 轉換擴展類 /// </summary> public static partial class Extensions { #region 轉換為long /// <summary> /// 將object轉換為long,若轉換失 ...
記錄下在開發中經常用到的類型轉換
/// <summary> /// 轉換擴展類 /// </summary> public static partial class Extensions { #region 轉換為long /// <summary> /// 將object轉換為long,若轉換失敗,則返回0。不拋出異常。 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static long ParseToLong(this object obj) { try { return long.Parse(obj.ToString() ?? string.Empty); } catch { return 0L; } } /// <summary> /// 將object轉換為long,若轉換失敗,則返回指定值。不拋出異常。 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static long ParseToLong(this string str, long defaultValue) { try { return long.Parse(str); } catch { return defaultValue; } } #endregion #region 轉換為int /// <summary> /// 將object轉換為int,若轉換失敗,則返回0。不拋出異常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static int ParseToInt(this object str) { try { return Convert.ToInt32(str); } catch { return 0; } } /// <summary> /// 將object轉換為int,若轉換失敗,則返回指定值。不拋出異常。 /// null返回預設值 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static int ParseToInt(this object str, int defaultValue) { if (str == null) { return defaultValue; } try { return Convert.ToInt32(str); } catch { return defaultValue; } } #endregion #region 轉換為short /// <summary> /// 將object轉換為short,若轉換失敗,則返回0。不拋出異常。 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static short ParseToShort(this object obj) { try { return short.Parse(obj.ToString() ?? string.Empty); } catch { return 0; } } /// <summary> /// 將object轉換為short,若轉換失敗,則返回指定值。不拋出異常。 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static short ParseToShort(this object str, short defaultValue) { try { return short.Parse(str.ToString() ?? string.Empty); } catch { return defaultValue; } } #endregion #region 轉換為demical /// <summary> /// 將object轉換為demical,若轉換失敗,則返回指定值。不拋出異常。 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static decimal ParseToDecimal(this object str, decimal defaultValue) { try { return decimal.Parse(str.ToString() ?? string.Empty); } catch { return defaultValue; } } /// <summary> /// 將object轉換為demical,若轉換失敗,則返回0。不拋出異常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static decimal ParseToDecimal(this object str) { try { return decimal.Parse(str.ToString() ?? string.Empty); } catch { return 0; } } #endregion #region 轉化為bool /// <summary> /// 將object轉換為bool,若轉換失敗,則返回false。不拋出異常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool ParseToBool(this object str) { try { return bool.Parse(str.ToString() ?? string.Empty); } catch { return false; } } /// <summary> /// 將object轉換為bool,若轉換失敗,則返回指定值。不拋出異常。 /// </summary> /// <param name="str"></param> /// <param name="result"></param> /// <returns></returns> public static bool ParseToBool(this object str, bool result) { try { return bool.Parse(str.ToString() ?? string.Empty); } catch { return result; } } #endregion #region 轉換為float /// <summary> /// 將object轉換為float,若轉換失敗,則返回0。不拋出異常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static float ParseToFloat(this object str) { try { return float.Parse(str.ToString() ?? string.Empty); } catch { return 0; } } /// <summary> /// 將object轉換為float,若轉換失敗,則返回指定值。不拋出異常。 /// </summary> /// <param name="str"></param> /// <param name="result"></param> /// <returns></returns> public static float ParseToFloat(this object str, float result) { try { return float.Parse(str.ToString() ?? string.Empty); } catch { return result; } } #endregion #region 轉換為Guid /// <summary> /// 將string轉換為Guid,若轉換失敗,則返回Guid.Empty。不拋出異常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static Guid ParseToGuid(this string str) { try { return new Guid(str); } catch { return Guid.Empty; } } #endregion #region 轉換為string /// <summary> /// 將object轉換為string,若轉換失敗,則返回""。不拋出異常。 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string ParseToString(this object obj) { try { return obj == null ? string.Empty : obj.ToString(); } catch { return string.Empty; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string ParseToStrings<T>(this object obj) { try { if (obj is IEnumerable<T> list) { return string.Join(",", list); } return obj.ToString(); } catch { return string.Empty; } } #endregion #region 轉換為double /// <summary> /// 將object轉換為double,若轉換失敗,則返回0。不拋出異常。 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static double ParseToDouble(this object obj) { try { return double.Parse(obj.ToString() ?? string.Empty); } catch { return 0; } } /// <summary> /// 將object轉換為double,若轉換失敗,則返回指定值。不拋出異常。 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static double ParseToDouble(this object str, double defaultValue) { try { return double.Parse(str.ToString() ?? string.Empty); } catch { return defaultValue; } } #endregion #region 強制轉換類型 /// <summary> /// 強制轉換類型 /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="source"></param> /// <returns></returns> public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source) { return from object item in source select (TResult)Convert.ChangeType(item, typeof(TResult)); } #endregion #region 轉換為ToUnixTime public static long ParseToUnixTime(this DateTime nowTime) { var startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); return (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero); } #endregion #region List轉DataTable /// <summary> /// List轉DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> public static DataTable ListToDataTable<T>(IEnumerable<T> list) { //創建屬性的集合 List<PropertyInfo> pList = new List<PropertyInfo>(); //獲得反射的入口 Type type = typeof(T); DataTable dt = new DataTable(); //把所有的public屬性加入到集合 並添加DataTable的列 Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); var theType = p.PropertyType; //處理可空類型 if (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(theType)); } else { dt.Columns.Add(p.Name, theType); } }); foreach (var item in list) { //創建一個DataRow實例 DataRow row = dt.NewRow(); //給row 賦值 pList.ForEach(p => { var v = p.GetValue(item, null); row[p.Name] = v == null ? DBNull.Value : v; }); //加入到DataTable dt.Rows.Add(row); } return dt; } /// <summary> /// List轉DataTable /// </summary> /// <param name="list"></param> /// <returns></returns> public static DataTable ListToDataTableNew(List<dynamic> list) { Dictionary<string, string> dic = new Dictionary<string, string>(); DataTable dt = new DataTable(); if (list != null && list.Count > 0) { foreach (var item in list[0]) { string text = item.ToString(); string key = text.Substring(1, text.IndexOf(',') - 1); string value = text.Substring(text.IndexOf(',') + 1, text.Length - text.IndexOf(',') - 2); dt.Columns.Add(key); } } foreach (var vlist in list) { DataRow row = dt.NewRow(); foreach (var item in vlist) { string text = item.ToString(); string key = text.Substring(1, text.IndexOf(',') - 1); string value = text.Substring(text.IndexOf(',') + 1, text.Length - text.IndexOf(',') - 2); //創建一個DataRow實例 row[key] = value; } //加入到DataTable dt.Rows.Add(row); } return dt; } #endregion #region 處理Excel單元格特殊字元 /// <summary> /// 處理Excel單元格特殊字元 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ExcelCellHandle(string str) { return ToSBC(str.Replace("\n", string.Empty).Replace("_", string.Empty).Replace(" ", string.Empty).Replace("'", string.Empty)); } /// <summary> /// 轉化為半形字元串(擴展方法) /// </summary> /// <param name="input">要轉化的字元串</param> /// <returns>半形字元串</returns> public static string ToSBC(string input)//single byte charactor { char[] c = input.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 12288)//全形空格為12288,半形空格為32 { c[i] = (char)32; continue; } if (c[i] > 65280 && c[i] < 65375)//其他字元半形(33-126)與全形(65281-65374)的對應關係是:均相差65248 c[i] = (char)(c[i] - 65248); } return new string(c); } #endregion #region 刪除最後一個字元之後的字元 /// <summary> /// 刪除最後結尾的一個逗號 /// </summary> public static string DelLastComma(string str) { return str.Substring(0, str.LastIndexOf(",")); } /// <summary> /// 刪除最後結尾的指定字元後的字元 /// </summary> public static string DelLastChar(string str, string strchar) { return str.Substring(0, str.LastIndexOf(strchar)); } /// <summary> /// 刪除最後結尾的長度 /// </summary> /// <param name="str"></param> /// <param name="Length"></param> /// <returns></returns> public static string DelLastLength(string str, int Length) { if (string.IsNullOrEmpty(str)) return ""; str = str.Substring(0, str.Length - Length); return str; } #endregion }