我学习C#,并尝试编写简单的应用程序。想问您有关如何在下面帮助我优化代码的问题。我写了两种方法,并考虑将其与yield和LINQ结合使用。想想是否有可能?
public List<string> getsSubpagesUrls(int subpages)
{
List<string> subpagesUrls= new List<string>();
for (int i = 1; i < subpages; i++)
{
string singleUrl = $"url/search%&page={i}";
subpagesUrls.Add(singleUrl);
}
return subpagesUrls;
}
public List<string> getAllAnnouncementIds(int numberOfSubpages)
{
List<string> annIds = new List<string>();
foreach (var url in getsSubpagesUrls(numberOfSubpages))
{
HtmlWeb web = new HtmlWeb();
var htmlDoc = web.Load(url);
var htmlBody = htmlDoc.DocumentNode.SelectNodes("//xpath");
var ids = htmlBody.Elements("element");
foreach (var id in ids)
{
annIds.Add(id.Attributes["data-item-id"].Value);
}
}
return annIds;
}
要使用yield
关键字,您需要从函数中返回IEnumerable,我对代码进行了一些重构:
public IEnumerable<string> getsSubpagesUrls(int subpages)
=> Enumerable.Range(1, subpages).Select(i => new string($"url/search%&page={i}"));
public IEnumerable<string> getAllAnnouncementIds(int numberOfSubpages)
{
HtmlWeb web = new HtmlWeb();
foreach (var url in getsSubpagesUrls(numberOfSubpages))
{
var htmlDoc = web.Load(url);
var htmlBody = htmlDoc.DocumentNode.SelectNodes("//xpath");
var ids = htmlBody.Elements("element");
foreach (var id in ids)
{
yield return id.Attributes["data-item-id"].Value;
}
}
}