我正在使用以下代码将HTML解析为数组。
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var html = e.Result;
var doc = new HtmlDocument();
doc.LoadHtml(html);
var list = doc.DocumentNode.Descendants("div").ToList();
var node = doc.DocumentNode.Descendants("table")
.FirstOrDefault(x => x.Id == "departures")
.Element("tbody") .Elements("tr")
.Select(tr => tr.Elements("td")
.Select(td => td.InnerText).ToArray()).ToArray();
然后,我将使用以下代码输出到Texblock。
//first line
textBlock1.Text = node[0][0];
textBlock2.Text = node[0][1];
textBlock3.Text = node[0][2];
//Second line
textBlock4.Text = node[1][0];
textBlock5.Text = node[1][1];
textBlock6.Text = node[1][2];
//Third line
textBlock7.Text = node[2][0];
textBlock8.Text = node[2][1];
textBlock9.Text = node[2][2];
我的问题是:HTM1每天都在变化,因此有时没有[2],有时最多[12]。
我想知道的是,我如何才能使用条件语句来检查数组是否存在,并且仅在有值的情况下才输出。
我已经尝试过类似下面的条件语句,但是当没有任何node [2]或node [1]结果时,它仍显示未处理的异常
if (node[2][0].length > 0)
{
textBlock1.Text = node[2][0];
}
任何帮助将不胜感激。如果您需要对此进行澄清,请告诉我。
最佳答案
为避免索引无效,必须确保所有尺寸,例如
if (node.length > 2 && node[2].length > 0) {
// Okay to use node[2][0]
// Since && is short-circuiting it will never make second
// check if first fails.
}
对我来说,一个更基本的问题似乎是文本框不是可变的,而是固定的(box1,box2等)。考虑改用其他控件,也许是列表控件。然后,可以均匀地添加
n
项(并且仅使用循环结构即可,而无需进行第一次索引检查)。文本框也可以动态创建,但这不是我的首选。快乐的编码。
关于c# - 如何检查数组是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7438831/