其中有列表的DataTable
问题描述:
我正在使用Linq将XML文件中的数据返回到DataTable并且工作正常。但是现在我试图修改代码来循环访问DataTable。我创建了一个自定义类来建模数据,并在我的模型中有一个List。当我通过DataTable循环显示记录时,它显示System.Collections.Generic.List`1 [System.String]而不是实际的数据。我不知道要搜索什么才能找到答案。其中有列表<string>的DataTable
段:
foreach (DataRow row in tbl.Rows)
{
myList = row["myList"] + ", " + myList;
}
的myList中列列表。我希望这是有道理的。
编辑:
public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
(rec,null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
答
hobbiesList = (List<string>)row["hobbies"];
foreach (var item in hobbiesList)
{
hobbies.Add(item.ToString());
}
hobby = string.Join(", ", hobbies.ToArray());
hobbies.Clear();
我不得不做以上才能正常工作。然后我将爱好添加到我的输出数组中。