You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 移除两个ArrayList中的重复行技术求助

移除两个ArrayList中重复行的解决方案

嘿,我看了你写的代码,已经完成了爬取Bing搜索结果URL的部分,现在要解决去重的问题对吧?咱们一步步来完善它:

首先提个小建议:尽量用**泛型的List<string>**代替非泛型的ArrayList,这样不仅类型更安全,还能避免不必要的装箱拆箱操作,代码可读性也更好。

接下来给你几种实现去重的方案,你可以根据需求选择:

方案一:遍历判断去重(最直观)

这种方法适合你想要保留Duplicated集合(存储所有爬取到的URL,包括重复的),同时让URLs只存唯一值的场景:

// 替换成泛型集合,类型更安全
List<string> URLs = new List<string>();
List<string> Duplicated = new List<string>();

byte[] data = wc.DownloadData("https://www.bing.com/search?q=" + keyword);
string htmlContent = Encoding.UTF8.GetString(data, 0, data.Length);
// 优化正则,匹配http/https开头的更多合法域名
MatchCollection M = Regex.Matches(htmlContent, @"https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}");

foreach (Match m in M)
{
    string url = m.Value;
    Duplicated.Add(url); // 保留所有爬取到的URL(含重复)
    // 只添加URLs中没有的项
    if (!URLs.Contains(url))
    {
        URLs.Add(url);
    }
}

方案二:用HashSet自动去重(效率更高)

如果不需要保留Duplicated集合,直接用HashSet<string>会更高效——因为它的Add方法会自动忽略重复元素:

HashSet<string> urlSet = new HashSet<string>();
byte[] data = wc.DownloadData("https://www.bing.com/search?q=" + keyword);
string htmlContent = Encoding.UTF8.GetString(data, 0, data.Length);
MatchCollection M = Regex.Matches(htmlContent, @"https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}");

foreach (Match m in M)
{
    urlSet.Add(m.Value); // 重复项会被自动跳过
}
// 转成List<string>方便后续操作
List<string> URLs = urlSet.ToList();

方案三:用LINQ的Distinct方法(最简洁)

如果你用的是.NET 3.5及以上版本,LINQ的Distinct()方法能一行搞定去重,代码非常简洁:

List<string> Duplicated = new List<string>();
byte[] data = wc.DownloadData("https://www.bing.com/search?q=" + keyword);
string htmlContent = Encoding.UTF8.GetString(data, 0, data.Length);
MatchCollection M = Regex.Matches(htmlContent, @"https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}");

foreach (Match m in M)
{
    Duplicated.Add(m.Value);
}
// 直接去重转成新的List
List<string> URLs = Duplicated.Distinct().ToList();

另外,我注意到你原来的正则表达式比较局限,只能匹配特定格式的URL,上面给的正则@"https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"可以匹配http和https开头的、带多级子域名的合法域名,适用性更广。

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:40:19