我有一个MVC网络应用程序,允许用户上传excel文件。 excel文件具有以下列数
我传递了一个DataTable
,它已根据上传的excel文件填充了列名。我已经开始创建一个class
,它有10个属性:
public class ImportData
{
public string OpertorName { get; set; }
public string MachineName { get; set; }
....
}
现在我想要实现的是从List<ImportData>
创建一个DataTable
。我知道我可以做以下事情
List<ImportData> imports = dt.AsEnumerable().Select(row =>
new ImportData
{
OpertorName = row.Field<string>("OPERTOR NAME"),
MachineName = row.Field<string>("MACHINE NAME")
...
//all 10 properties
}).ToList();
以上版本适用于File 1
,但我如何能够容纳其余文件,因为并非所有文件都包含DataTable
答案 0 :(得分:2)
您可以检查某个列是否存在,然后从DataTable
获取列值或设置一些默认值。像这样:
List<ImportData> imports = dt.AsEnumerable().Select(row =>
new ImportData
{
OpertorName = row.Field<string>("OPERTOR NAME"),
MachineName = row.Field<string>("MACHINE NAME"),
SomeOtherProperty = row.Table.Columns.Contains("column_name") ?
row.Field<string>("column_name") :
string.Empty //default value since column_name doesn't exist
//etc
}).ToList();