正在搜索 collection

Searching through a collection

1.The 下面的代码片段应该根据文档的标题通过通用排序例程进行搜索,我不确定它是否这样做。有帮助吗?

public Document searchByTitle (String aTitle)
{
  foreach(Document doc in this)
  {
    if (doc.Title == aTitle)
    {
      return doc;
    }
    else
    {
      return null;
    }
  }
}

2.This 代码片段应该显示一种返回存储在 collection 上的书籍数量的方法。这有意义吗?

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;
}

请注意,您应该 return null; 只有在 整个 集合被检查后。

我们经常使用Linq来查询集合,例如

using System.Linq;

...

public Document searchByTitle (String aTitle) 
{
  return this.FirstOrDefault(doc => doc.Title == aTitle);
}

编辑:与第二个片段完全相同的问题(过早 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");
 }