/// <summary>
/// 扩展:将object强制转化为int
/// </summary>
/// <param name="o">要强制转换的object</param>
/// <param name="defaultValue">o为null或者转换失败的默认值</param>
/// <returns></returns>
public static int TryToInt(this object o, int defaultValue = 0)
{//o为null 或者转换失败返回默认值int retValue = o == null || !int.TryParse(o.ToString(), out retValue) ? defaultValue : retValue;return retValue;
}/// <summary>
/// 将DataTable转为JObject
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static JArray DataTable2JArray(DataTable dt)
{if (dt == null || dt.Rows.Count == 0) return null;var ja = new JArray();foreach (DataRow dr in dt.Rows){ja.Add(DataRow2JObject(dr));}return ja;}/// <summary>
/// 将DataRow转为JObject
/// </summary>
/// <param name="dr"></param>
/// <returns></returns>
public static JObject DataRow2JObject(DataRow dr)
{if (dr == null) return null;var jo= new JObject();foreach (DataColumn column in dr.Table.Columns){switch (column.DataType.Name){case "Int32":jo.Add(column.ColumnName, dr[column].TryToInt(0));break;default:jo.Add(column.ColumnName, dr[column].ToString());break;}}return jo;
}
示例代码中只提供了Int32类型的处理,其它类型自己可以添加。