我的问题如下(c#环境):我在HTML文档中得到了一个表。我使用htmllagilitypack和正则表达式提取表。所有单元格都保存在一个字符串列表中。现在我想把这些表保存成二维数组,就像普通表一样。问题是,这些行的长度不一样。表格是这样写的(……)点是空白):
| aaa | 123 | 456 |
| .......| 986 | 468 |
| BBB | 507 | 206 |
| ........| 450 | 256 |
"aaa"在第一列中应用于第一行和第二行,";bbb"3次方。和4。行,等等。现在我需要一些逻辑来告诉Array以正确的方式从List中填充它,比如:
| aaa | 123 | 456 |
| aaa | 986 | 468 |
| BBB | 507 | 206 |
| BBB | 450 | 256 |
这些想法都不是固定的,我们不需要使用列表或数组,这些只是我的第一个想法。如果你有一个想法的逻辑来填补数组或一个完全不同的,但更好的方式,我会非常感谢!
重要编辑:丢失的单元格可以在表的任何列中,而不仅仅是在第一个位置!!如:
| aaa | 123 | 456 |
| aaa | .......| 468 |
| BBB | 507 | 206 |
| BBB | 450 | .......|
现在第二行中的点是属于"123";最后一行的点属于"206"。
string[,] DataArray = new string[4, 3]; // just an example size for the table above
List<string> Data = new List<string>(); // the cells from the HTML table are saved here
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(myHtmlDoc);
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
{
foreach (HtmlNode row in table.SelectNodes("tr"))
{
foreach (HtmlNode cell in row.SelectNodes("th|td"))
{
Data.Add(cell.InnerText);
}
}
}
for (int i = 0; i < DataArray.GetLength(0); i++)
{
for (int j = 0; j < DataArray.GetLength(1); j++)
{
// some logic in here to pick the right part of the List and put it in the
// right position in the Array
}
}
这里有一个解决方案,将为您使用Linq和返回字典工作。我很抱歉,因为我知道如果你是c#的新手,这可能不是很有意义。
我可以稍后再来补充更多的解释。我假设这些值可以被解析为int。在此解决方案中,不能解析为int的值将被丢弃。
string runningKey = "";
Dictionary<string, List<int>> dictionary =
doc.DocumentNode.SelectNodes("//table")
.SelectMany(t => t.SelectNodes("tr"))
.Select(tr => tr.SelectNodes("td|th").ToList())
.Where(tds => tds.Any())
.Select(
(tds) =>
{
runningKey = string.IsNullOrWhiteSpace(tds.First().InnerText) ? runningKey : tds.First().InnerText;
return
new
{
Key = runningKey,
Values =
tds
.Skip(1)
.Select(td => int.TryParse(td.InnerText, out int result) ? result : -1)
.Where(n => n != -1)
.ToList()
};
})
.GroupBy(v => v.Key)
.ToDictionary(g => g.Key, g => g.SelectMany(v => v.Values).ToList());
希望这对你有帮助!