1。下面的代码段应该按文档的标题通过通用排序例程进行搜索,但我不确定是否执行此操作。有帮助吗?
public Document searchByTitle (String aTitle)
{
foreach(Document doc in this)
{
if (doc.Title == aTitle)
{
return doc;
}
else
{
return null;
}
}
}
2。该代码段应该显示一种返回存储在集合中的书籍数量的方法。这有意义吗?
public static int NoofBooks()
{
int count = 0;
foreach(Document doc in this)
{
if (doc.Type == "Book")
{
count++;
}
return count;
}
}
否,您的代码是不正确,应该是:
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);
}
Edit:与第二个片段非常相同的问题(premature
return
): public static int NoofBooks()
{
int count = 0;
// scan the entire collection...
foreach(Document doc in this)
{
if (doc.Type == "Book")
{
count++;
}
}
// ..and only then return the answer
return count; // <- return should be here
}
或再次将其表示为Linq
public static int NoofBooks()
{
return this.Count(doc => doc.Type == "Book");
}