我有一个Linq查询,如下所示
var ResultQuery = from Task in dtTasks.AsEnumerable()
select new { EmployeeName = Task.Field<string>("EmpName").Split(':')[1],
EmployeeCode = Task.Field<string>("EmpName").Split(':')[0],
ProjectId = Task.Field<string>("ProjectName").Split(':')[0],
ProjectName = Task.Field<string>("ProjectName").Split(':')[1],
TaskName = Task.Field<string>("TaskName"),
TaskDescription = Task.Field<string>("TaskDescription"),
StartDate = Task.Field<DateTime>("StartDate"),
Duration = Task.Field<double>("Duration"),
EndDate = Task.Field<DateTime>("EndDate"),
LeadName = Task.Field<string>("LeadBy").Split(':')[1],
LeadId = Task.Field<string>("LeadBy").Split(':')[0]
};
foreach (var task in ResultQuery)
{
}
dtTasks
是Microsoft Excel文件中导入的表。由于它是用户输入文件,因此可能存在很多拼写错误。在Linq Query中,如果任何DateTime转换失败,或者对象引用未设置为实例错误(插入空行或空行时为String.Split
方法),我该如何处理?我想跳过这些迭代并向用户发出关于跳过原因的警告。如果我使用Linq,我怎样才能实现这个目标?
答案 0 :(得分:0)
一旦出现异常,就会破坏可枚举 - 您无法进一步迭代。
以下是解决方法:
var ResultQuery = dtTasks.AsEnumerable()
.Select(Task => {
try {
return new { EmployeeName = Task.Field<string>("EmpName").Split(':')[1],
EmployeeCode = Task.Field<string>("EmpName").Split(':')[0],
ProjectId = Task.Field<string>("ProjectName").Split(':')[0],
ProjectName = Task.Field<string>("ProjectName").Split(':')[1],
TaskName = Task.Field<string>("TaskName"),
TaskDescription = Task.Field<string>("TaskDescription"),
StartDate = Task.Field<DateTime>("StartDate"),
Duration = Task.Field<double>("Duration"),
EndDate = Task.Field<DateTime>("EndDate"),
LeadName = Task.Field<string>("LeadBy").Split(':')[1],
LeadId = Task.Field<string>("LeadBy").Split(':')[0]
}
} catch(Exception e) {
Console.WriteLine("Print your warning!");
return null;
}
});
foreach (var task in ResultQuery)
{
if(task != null) {
// do your processing
}
}