如何使用列表或数组进行此操作?

时间:2012-06-14 04:25:58

标签: c# arrays list loops

除此之外还有一切:links.Remove(linkToClick),因为HtmlElementCollection没有“删除”方法。

我最近在这里问了一个问题:How to have loop move to the next id available rather than doing the same continuously?

这就是推荐给我的,但我一直在寻找并试图在过去的两个小时内解决这个问题,但仍然无法弄明白。

HtmlElementCollection links = null;

private void button2_Click(object sender, EventArgs e)
{
    // This way you only get the links once.
    links = webBrowser1.Document.GetElementsByTagName("a");

    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    HtmlElement linkToClick = null;

    foreach (HtmlElement link in links)
    {
        if (link.GetAttribute("id").Contains("user"))
        {
            linkToClick = link;
            break;
        }
    }

    // did I find a link?
    if (linkToClick != null)
    {
        // Remove it from the list so you don't click it again.
        links.Remove(linkToClick);

        link.InvokeMember("click");
    }
}

1 个答案:

答案 0 :(得分:1)

List<HtmlElement> links = null;

private void button2_Click(object sender, EventArgs e)
{
    // This way you only get the links once.
    links = new List<HtmlElement>(webBrowser1.Document.GetElementsByTagName("a")
                                                      .Cast<HtmlElement>());

    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    HtmlElement linkToClick = null;

    foreach (HtmlElement link in links)
    {
        if (link.GetAttribute("id").Contains("user"))
        {
            linkToClick = link;
            break;
        }
    }

    // did I find a link?
    if (linkToClick != null)
    {
        // Remove it from the list so you don't click it again.
        links.Remove(linkToClick);

        linkToClick.InvokeMember("click");
    }
}

如果linkToClick == null我还建议在计时器内停止计时器,为什么你不提前过滤清单呢?

links = new List<HtmlElement>(webBrowser1.Document.GetElementsByTagName("a")
                                                  .Cast<HtmlElement>());

links.RemoveAll(link => !link.GetAttribute("id").Contains("user"));

在计时器中:

if (links.Count > 0)
{
    links[0].InvokeMember("click");
    links.RemoveAt(0);
}
// else timer.Stop();