请教下json字符串转datatable出现问题

CalvinR 2014-12-15 06:06:11
 public static DataTable ListToDataTable<T>(List<T> entitys)
{
//检查实体集合不能为空
if (entitys == null || entitys.Count < 1)
{
throw new Exception("需转换的集合为空");
}
//取出第一个实体的所有Propertie
Type entityType = entitys[0].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();

//生成DataTable的structure
//生产代码中,应将生成的DataTable结构Cache起来,此处略
DataTable dt = new DataTable();
for (int i = 0; i < entityProperties.Length; i++)
{
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(entityProperties[i].Name);
}
//将所有entity添加到DataTable中
foreach (object entity in entitys)
{
//检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entityValues);
}
return dt;
}



entityValues[i] = entityProperties[i].GetValue(entity, null); 参数计数不匹配。
...全文
308 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
CalvinR 2014-12-16
  • 打赏
  • 举报
回复
引用 2 楼 bdmh 的回复:
GetValue的第二个参数是索引化属性的可选索引值。 对于非索引化属性,才为null,如果是索引化属性,就不能是null
请教下那我该怎么解决呢?
smthgdin_020 2014-12-16
  • 打赏
  • 举报
回复
entityValues[i] = entityProperties[i].GetValue(entity, null); 参数计数不匹配。 你确定所有的属性都是非索引属性?
bdmh 2014-12-16
  • 打赏
  • 举报
回复
GetValue的第二个参数是索引化属性的可选索引值。 对于非索引化属性,才为null,如果是索引化属性,就不能是null
Forty2 2014-12-16
  • 打赏
  • 举报
回复
有些属性需要参数,有些只写,要过滤掉: PropertyInfo[] entityProperties = entityType .GetProperties() .Where(p => p.CanRead && p.GetIndexParameters().Length == 0) .ToArray();
蝶恋花雨 2014-12-16
  • 打赏
  • 举报
回复
若要使用 GetValue 方法,请先获取类 Type。 从 Type 获取 PropertyInfo。 从 PropertyInfo 使用 GetValue 方法。 参考 http://msdn.microsoft.com/zh-cn/library/b05d59ty.aspx demo: http://www.cnblogs.com/dyfzwj/archive/2011/04/16/2017916.html
public DataTable FillDataTable(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
            DataTable dt = CreateData(modelList[0]);

            foreach(T model in modelList)
            {
                DataRow dataRow = dt.NewRow();
                foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
                {
                    dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
                }
                dt.Rows.Add(dataRow);
            }
            return dt;
        }

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧