搜索集合

时间:2019-12-27 13:47:21

标签: c# search collections return generic-collections

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

1 个答案:

答案 0 :(得分:1)

否,您的代码是不正确,应该是:

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");
 } 
相关问题