我在SQL的foreach循环中使用DataTable
,例如:
foreach(var i in tasks)
{
// query sql
var timeOfTasks = db.GetTableBySQL($"exec usp_Get_WorkedProyectTime @TaskTypeCategoryId = '{i.TaskTypeCategoryId}', @TaskId= '{i.TaskId}'");
// read columns (different rows have different columns)
var progressToBackCheck = (from DataRow dr in timeOfTasks.Rows select dr["ProgressToBackCheck"]).FirstOrDefault();
var backcheckToCorrection = (from DataRow dr in timeOfTasks.Rows select dr["BackcheckToCorrection"]).FirstOrDefault();
var correctionsToCompleted = (from DataRow dr in timeOfTasks.Rows select dr["CorrectionsToCompleted"]).FirstOrDefault();
var progressToCompleted = (from DataRow dr in timeOfTasks.Rows select dr["ProgressToCompleted"]).FirstOrDefault();
}
并非所有任务结果都具有相同的数据行。而且每一行都不包含所有字段。在使用查询之前,是否可以检查结果中是否存在一列?
答案 0 :(得分:3)
您可以尝试使用DataColumnCollection.Contains来检查数据表中是否存在该列。
if (timeOfTasks.Columns.Contains("ProgressToBackCheck"))
{
}
您可以使用此linq获取字段,添加where
linq
where timeOfTasks.Columns.Contains("ProgressToBackCheck")
看起来像这样。
var progressToBackCheck = (
from DataRow dr in timeOfTasks.Rows
where timeOfTasks.Columns.Contains("ProgressToBackCheck")
select dr["ProgressToBackCheck"]
).FirstOrDefault();