您的位置:首页 > Web前端 > JavaScript

DataSet、DataTable、Json、List 等各种数据的相互转化

2015-07-30 09:30 716 查看
1.根据Dataset生成json格式的字符串,不管Dataset里面有多少个表都可以一一生成对应的json字符串,并一次性返回

private string dsToJson(DataSet ds)
{
System.Text.StringBuilder str = new System.Text.StringBuilder("[");
for (int o = 0; o < ds.Tables.Count; o++)
{
str.Append("{");
str.Append(string.Format("\"{0}\":[", ds.Tables[o].TableName));

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
str.Append("{");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
str.Append(string.Format("\"{0}\":\"{1}\",", ds.Tables[0].Columns[j].ColumnName, ds.Tables[0].Rows[i][j].ToString()));
}
str.Remove(str.Length - 1, 1);
str.Append("},");
}
str.Remove(str.Length - 1, 1);
str.Append("]},");
}
str.Remove(str.Length - 1, 1);
str.Append("]");
return str.ToString();
}


2.数据库中的内容转换成json数据

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
private string dsToJson()
{
System.Text.StringBuilder str = new System.Text.StringBuilder("[");
for (int o = 0; o < ds.Tables.Count; o++)
{
str.Append("{");
str.Append(string.Format("\"{0}\":[", ds.Tables[o].TableName));

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
str.Append("{");
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
str.Append(string.Format("\"{0}\":\"{1}\",", ds.Tables[0].Columns[j].ColumnName, ds.Tables[0].Rows[i][j].ToString()));
}
str.Remove(str.Length - 1, 1);
str.Append("},");
}
str.Remove(str.Length - 1, 1);
str.Append("]},");
}
str.Remove(str.Length - 1, 1);
str.Append("]");

return str.ToString();
}


3.C# - list<>数据填充到Dataset里

publicstatic DataSet ConvertToDataSet<T>(IList<T> list)
{
if (list ==null|| list.Count <=0)
{
returnnull;
}
DataSet ds =new DataSet();
DataTable dt =new DataTable(typeof(T).Name);
DataColumn column;
DataRow row;

System.Reflection.PropertyInfo[] myPropertyInfo =typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
foreach (T t in list)
{
if (t ==null)
{
continue;
}
row = dt.NewRow();
for (int i =0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string name = pi.Name;
if (dt.Columns[name] ==null)
{
column =new DataColumn(name, pi.PropertyType);
dt.Columns.Add(column);
}
row[name] = pi.GetValue(t, null);
}
dt.Rows.Add(row);
}
ds.Tables.Add(dt);
return ds;
}
}


4.DataSet 和 Datable 的相互转化

DataSet ds = DbHelperSQL.Query("select * from text_table where a='3'");
string strtext = ds.Tables[0].Rows[0]["bz"].ToString();


5.List转化成数组

List<string> a = new List<string>();
public string[] getString(TreeNodeCollection item)
{
NumMethod(item);
return a.ToArray();
}


6.将字符转转化成数组并以逗号分割,即,去掉逗号

string strszcdid = "1111,111111,111112,111211,111311,";

string[] a = strszcdid.Split(',');


7.截取字符转从字符串指定位置截取到固定的长度

id = id.Substring(0, id.Length - 1);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: