C# 如何将列表转换为数据表
我有一个类正在从C# 如何将列表转换为数据表,c#,json,C#,Json,我有一个类正在从JSONtext转换 这是我的密码 SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult)); 而SearchResult类是 public class SearchResult { public List<Datum> data { get; set; } public int page { get; set; }
JSON
text转换
这是我的密码
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
而SearchResult
类是
public class SearchResult
{
public List<Datum> data { get; set; }
public int page { get; set; }
public int per_page { get; set; }
public int total_count { get; set; }
public string search_id { get; set; }
}
public class Datum
{
public string id { get; set; }
public string description { get; set; }
public string added_date { get; set; }
public string media_type { get; set; }
public Contributor contributor { get; set; }
public string aspect { get; set; }
public string image_type { get; set; }
public bool is_editorial { get; set; }
public bool is_adult { get; set; }
public bool is_illustration { get; set; }
public bool has_model_release { get; set; }
public bool has_property_release { get; set; }
public List<string> releases { get; set; }
public List<Category> categories { get; set; }
public List<string> keywords { get; set; }
public Assets assets { get; set; }
public List<Model> models { get; set; }
}
我想将SearchResult
类的列表data
转换为datatable
。
对于转换,我使用的是答案。
但不知道如何用Listdata
调用它
请帮助我解决这个问题
我只想要一个数据表,它只包含
列表
因为您已经有了该方法,所以它很简单:
DataTable tblDatum = ToDataTable(myobj.data)
如果您已经从json获得了带有数据的搜索结果。 根据你的Stackoverflow链接。将列表转换为datatable的代码如下:
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
SearchResult myobj = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
if (myobj.data != null && myobj.data.Count > 0)
{
DataTable dt = ToDataTable(myobj.data);
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow item in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
Console.WriteLine(item[dc]);
}
}
}
}
顺便说一下,DataTable的名称是可选的,因此您也可以编写:
YourList.CreateDataTable();
你提供的链接正是你所需要的。你能告诉我到目前为止你的代码和哪里有问题吗?提示:Microsoft建议属性名使用大写。您有一个方法可以接受任何类型的通用列表,如
List
。因此,只需将其作为参数传递,就可以得到DataTable
。有什么问题吗?@TimSchmelter先生,我不知道如何用myojb.data
或什么来称呼它?@Gitz:你想要一个DataTable
只包含列表中的行,还是想要一个同时包含搜索结果的所有属性的表?如果前者:DataTable result=ToDataTable(myobj.data)
ToDataTable(myojb.data);
YourList.CreateDataTable();