我正在使用以下格式从Excel工作表中读取数据 -
我需要以下列方式存储数据 -
我试图在Linq lambda表达的帮助下做到这一点,但我想我没有得到这个。
我尝试了什么 -
DataTable dataTable= ReadExcel();
var dt = dataTable.AsEnumerable();
var resultSet = dt.Where(x => !String.IsNullOrEmpty(x.Field<String>("Project_Code")))
.GroupBy(x =>
new
{
Month = x.Field<String>("Month"),
ProjectCode = x.Field<String>("Project_Code"),
//change designation columns into row data and then group on it
//Designation =
}
);
//.Select(p =>
// new
// {
// Month= p.d
// }
// );`
答案 0 :(得分:2)
我会使用带有预定义指定名称的ToDictionary:
private static readonly string[] designationNames = {"PA","A","SA","M","SM","CON"};
void Function()
{
/* ... */
var resultSet = dt.AsEnumerable().Where(x => !String.IsNullOrEmpty(x.Field<String>("Project_Code")))
.Select(x =>
new
{
Month = x.Field<String>("Month"),
ProjectCode = x.Field<String>("Project_Code"),
Designations = designationNames.ToDictionary(d => d, d => x.Field<int>(d))
}
);
}
这是规范化版本。如果你想要它变平,请使用:
private static readonly string[] designationNames = {"PA","A","SA","M","SM","CON"};
void Function()
{
/* ... */
var resultSet = dt.AsEnumerable().Where(x => !String.IsNullOrEmpty(x.Field<String>("Project_Code")))
.Select(x =>
designationNames.Select(
d =>
new
{
Month = x.Field<String>("Month"),
ProjectCode = x.Field<String>("Project_Code"),
Designation = d,
Count = x.Field<int>(d)
}
)
).SelectMany(x => x).ToList();
}
如果类型不总是int,那么您可能希望使用x.Field<String>(d)
来检查有效性。