0
    private void button1_Click(object sender, EventArgs e)
    {
        test();
    }


    public void test()
    {

        Dictionary<string, string> LnksDict = new Dictionary<string, string>();

        using (SmartWebClient smwc = new SmartWebClient())
        {

            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(smwc.DownloadString("http://www.google.com/adplanner/static/top1000/"));
            var links = htmlDoc.DocumentNode
                            .Descendants("a").Select(x => x.Attributes["href"]);
            foreach (var link in htmlDoc.DocumentNode.SelectNodes("//a"))
            {
                var UrlVal= link.Attributes["href"].Value;
                var name = UrlVal.Split('.')[1];

                LnksDict.Add(name, UrlVal);
            } 
        }
    }

#region <<=========== SmWbCl ============>>

public class SmartWebClient : WebClient
{
    private readonly int maxConcurentConnectionCount;

    public SmartWebClient(int maxConcurentConnectionCount = 20)
    {

        this.maxConcurentConnectionCount = maxConcurentConnectionCount;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var httpWebRequest = (HttpWebRequest)base.GetWebRequest(address);
        if (httpWebRequest == null)
        {
            return null;
        }

        if (maxConcurentConnectionCount != 0)
        {
            this.Proxy = null;
            this.Encoding = Encoding.GetEncoding("UTF-8");
            httpWebRequest.ServicePoint.ConnectionLimit = maxConcurentConnectionCount;
        }

        return httpWebRequest;
    }

}

#endregion

このコードでは、後で autoComplete ソースとして使用する URL のリストを作成しようとしています。

私が間違っているのは、解析された値を辞書に追加することを条件としていないことです。

すでに存在する場合でも、ドメイン名をキーとして追加する方法を見つける必要があります。

だから私は条件を作ることができるようにしたいと思います:

この辞書の が既に存在する場合は、接尾辞としてof currentをkey追加しますcollection indexlinkstring.valuekey

または、別の解決策をまとめて提案したい場合は...新しい例を見て喜んでいます。ありがとう

4

1 に答える 1

1

Dictionary<string, string>あなたが望むのは ではなく だと思いますDictionary<string, HashSet<string>>。そうすれば、各ドメインの URL のリストを作成できます。リストにアイテムを追加するコードは次のようになります。

var UrlVal= link.Attributes["href"].Value;
var name = UrlVal.Split('.')[1];

// get links for this host
HashSet hostLinksList;
if (!LnksDict.TryGetValue(name, out hostLinksList))
{
    hostLinksList = new HashSet<string>();
    LnksDict.Add(name, hostLinksList);
}
// add the URL to the list of links for this host
hostLinksList.Add(UrlVal);

ここで重要なのは、アイテムが既に存在するときAddに aを呼び出してHashSetも例外がスローされないことです。再度追加せずfalse、アイテムが既にコレクションにあったことを示すために戻ります。

完了すると、各ホスト (ドメイン) の URL のリストが作成され、オートコンプリートに使用できます。

ところで、使用してホストを分割する方法はSplit('.')あまりうまくいきません。「www.example.com」という形式のドメインを想定しています。たとえば、「example.com」(「www」なし) に出くわした場合、名前は「com」になります。また、「www.example.com」は「www.example.org」および「www.example.co.uk」と衝突します。ホストを識別するより良い方法が必要です。

于 2012-11-28T04:25:12.683 に答える