我正在以下列格式从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
// }
// );`
最佳答案 我会使用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)来检查有效性.