首页 > 解决方案 > C# foreach 重复 300+ 次

问题描述

我有一个程序,它加载一个带有表格的本地 HTML 页面,它将从中提取几个结果,并将其集成到 DataGridView 中。

[返回问题的程序的图像...]:

https://i.stack.imgur.com/43iNt.jpg

问题来了,我正在使用 foreach 并且它重复操作 300 多次......

我不明白,也找不到问题出在哪里。你能启发我吗?谢谢。

[我试图从中提取数据的 HTML 代码]:

<table cellspacing="0" cellpadding="0" border="0" style="border-width:0px;width:809pt;border-collapse:collapse;">
<tbody>
<tr style="height:16.4pt;">
<td class="sd2f9551a" style="width:42.9pt;height:16.4pt;"></td>
<td class="s054608a3" style="height:15.7pt;padding:2px 2px 2px 2px;width:70.8pt;">601</td>
<td class="s828d7148" style="height:15.7pt;padding:2px 2px 2px 2px;width:106.6pt;">001834820601</td>
<td class="s828d7148" colspan="7" style="height:15.7pt;padding:2px 2px 2px 2px;width:128.1pt;"></td>
<td class="s828d7148" colspan="3" style="height:15.7pt;padding:2px 2px 2px 2px;width:121pt;"></td>
<td class="sf7752056" colspan="6" style="height:15.7pt;padding:2px 2px 2px 2px;width:214pt;"></td>
<td class="s054608a3" style="height:15.7pt;padding:2px 2px 2px 2px;width:78pt;">EMBARCADO</td>
<td class="s9a0851f4" style="width:42.9pt;height:16.4pt;"></td>
</tr>
<tr style="height:15.7pt;">
<td class="sd2f9551a" style="width:42.9pt;height:15.7pt;"></td>
<td class="s054608a3" style="height:15pt;padding:2px 2px 2px 2px;width:70.8pt;">602</td>
<td class="s828d7148" style="height:15pt;padding:2px 2px 2px 2px;width:106.6pt;">001834820602</td>
<td class="s828d7148" colspan="7" style="height:15pt;padding:2px 2px 2px 2px;width:128.1pt;"></td>
<td class="s828d7148" colspan="3" style="height:15pt;padding:2px 2px 2px 2px;width:121pt;"></td>
<td class="sf7752056" colspan="6" style="height:15pt;padding:2px 2px 2px 2px;width:214pt;"></td>
<td class="s054608a3" style="height:15pt;padding:2px 2px 2px 2px;width:78pt;">EMBARCADO</td>
<td class="s9a0851f4" style="width:42.9pt;height:15.7pt;"></td>
</tr>
</tbody>
</table>

[返回问题的代码片段...]:

foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//tbody"))
            {
                foreach (HtmlNode row in table.SelectNodes("//tr[(@style='height:16.4pt;') or (@style='height:15.7pt;')]"))
                {
                    DataRow r = dt.NewRow();
                    int i = 0;

                    HtmlNodeCollection cells = row.SelectNodes("td");
                    if (cells == null)
                        continue;
                    foreach (HtmlNode cell in cells)
                    {
                        r[i] = cell.InnerText;
                        i++;
                    }
                    dt.Rows.Add(r);
                }
            }

标签: c#foreachdatagridview

解决方案


推荐阅读