这里有一个代码2 DataTables
。它们都填充了SQL Server 2012中的SqlDataAdabter
。dtParticipants
中有15.000行,dtSubjectResult
中有80.000行。
foreach (DataRow rowPart in dtParticipants.Rows)
{
int partId = int.Parse(rowPart["main_id"].ToString());
string partUserCode = rowPart["o_user_code"].ToString();
DataRow[] filteredRows = dtSubjectResult.Select("main_id = " + partId);
if (filteredRows == null)
continue;
foreach (DataRow row in filteredRows)
{
row["correct_count"] = 5;//unit.CorrectCount;
row["incorrect_count"] = 15;//unit.IncorrectCount;
row["empty_count"] = 20;//unit.EmptyCount;
row["net_count"] = 12;//unit.Total;
}//foreach 2
}//foreach 1
但是这段代码非常慢......当我在第二个foreach中注释代码时,代码运行非常正常,没有任何速度问题。
有趣的是,当我尝试这样的代码时,它的效果非常好。
foreach (DataRow row in dtSubjectResult.Rows)
{
row["correct_count"] = 5;//unit.CorrectCount;
row["incorrect_count"] = 15;//unit.IncorrectCount;
row["empty_count"] = 20;//unit.EmptyCount;
row["net_count"] = 12;//unit.Total;
}
那么问题是什么... IS循环过滤的行慢?我不知道??
答案 0 :(得分:1)
多重过滤操作是一个严重的性能损失
DataRow[] filteredRows = dtSubjectResult.Select("main_id = " + partId);
Select
需要解释过滤器表达式,在每次15k迭代中扫描dtSubjectResult
中的80k行
Join
2个表并一次更新dtSubjectResult
行:
var grouped = dtParticipants.AsEnumerable()
.Join(dtSubjectResult.AsEnumerable(),
rPart => (int)rPart["main_id"],
rSubj => (int)rSubj["main_id"],
(rPart, rSubj) => new { P = rPart, S = rSubj })
.GroupBy(x => x.P["main_id"]);
foreach (var gr in grouped)
{
foreach (var row in gr)
{
row.S["correct_count"] = 5;//unit.CorrectCount;
row.S["incorrect_count"] = 15;//unit.IncorrectCount;
row.S["empty_count"] = 20;//unit.EmptyCount;
row.S["net_count"] = 12;//unit.Total;
}
}