下面的代码段应该按文档的标题通过通用排序例程进行搜索,但我不确定是否执行此操作。有帮助吗?
public Document searchByTitle (String aTitle)
{
foreach(Document doc in this)
{
if (doc.Title == aTitle)
{
return doc;
}
else
{
return null;
}
}
}
否,您的代码在[[不正确中,应为
public Document searchByTitle (String aTitle)
{
foreach(Document doc in this)
{
if (doc.Title == aTitle)
{
return doc; // if we have found the required doc we return it
}
}
// we've scanned the entire collection and haven't find anything
// we return null in such a case
return null;
}
请注意,只有在检查了[[entire集合之后,才应该
return null;
。通常,我们使用Linq来查询集合,例如
using System.Linq;
...
public Document searchByTitle (String aTitle)
{
return this.FirstOrDefault(doc => doc.Title == aTitle);
}