Last active
December 17, 2017 08:47
-
-
Save hellojinjie/f38f9c576692a11d6a74da4d0de6033b to your computer and use it in GitHub Desktop.
C# DataTable to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Utils | |
{ | |
public static object DataTableToObject(DataTable dataTable) | |
{ | |
var list = new List<object>(); | |
foreach (DataRow row in dataTable.Rows) | |
{ | |
var pairList = new List<KeyValuePair<string, object>>(); | |
foreach (DataColumn column in dataTable.Columns) | |
{ | |
var value = row[column]; | |
if (column.DataType == typeof(DateTime)) | |
{ | |
value = ((DateTime)row[column]).ToString("yyyy-MM-dd hh:mm:ss"); | |
} | |
var pair = new KeyValuePair<string, object>(column.ColumnName, value); | |
pairList.Add(pair); | |
} | |
list.Add(pairList.ToDictionary(x => x.Key, x => x.Value)); | |
} | |
return list; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[WebMethod(EnableSession=true)] | |
public static object GetFreePhoto(string month, string volume) | |
{ | |
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString); | |
conn.Open(); | |
var sqlCommand = new SqlCommand | |
{ | |
Connection = conn, | |
CommandText = "select * from dbo.iva_free_photo where month=@month and volume=@volume" | |
}; | |
sqlCommand.Parameters.AddWithValue("@month", month.Substring(0, 4) + "-" + month.Substring(4, 2) + "-01"); | |
sqlCommand.Parameters.AddWithValue("@volume", volume); | |
var sda = new SqlDataAdapter(sqlCommand); | |
var ds = new DataSet(); | |
sda.Fill(ds); | |
var result = Utils.DataTableToObject(ds.Tables[0]); | |
conn.Close(); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment