Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将列表对象转换为数据表_C#_Asp.net Mvc - Fatal编程技术网

C# 无法将列表对象转换为数据表

C# 无法将列表对象转换为数据表,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个JSON对象,我从一个ajax post调用中得到它,我将它映射到我的Customclass对象列表中,如下所示 [ObjectFilter(Param = "postdata", RootType = typeof(List<ExportToExcel8020>))] public void ExportToExcel(List<ExportToExcel8020> text) { //List<

我有一个
JSON
对象,我从一个ajax post调用中得到它,我将它映射到我的Customclass对象列表中,如下所示

[ObjectFilter(Param = "postdata", RootType = typeof(List<ExportToExcel8020>))]
        public void ExportToExcel(List<ExportToExcel8020> text) 
        
{
  //List<ExportToExcel8020> rm = text.AsEnumerable().ToList();
  //DataTable UserDt = rm .ToDataTable();
  DataTable UserDt = text.ToDataTable();
}
我之所以需要它作为
datatable
是为了使用
openxml
并导出
excel
文件


我的代码有问题吗?还是我的方法本身是错误的?

这看起来像是您正在尝试编写一个扩展方法。方法签名需要将
this
作为第一个参数的关键字,该参数随后指定要扩展的类型(并在调用扩展方法时传入对象实例)。试一试

公共静态数据表到数据表(此列表项)

作为方法签名。

看起来您正在尝试创建扩展方法。您需要执行
公共静态数据表到数据表(此列表项)
。谢谢@skintkingle,这很有效。我想补充一点信息,该方法也应该在静态类中编写,因为这是一个扩展方法。
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;
        }
public static DataTable ToDataTable<T>(this List<T> items)