搜索集合

问题描述 投票:-1回答:1

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;    
  }
}
c# search collections return generic-collections
1个回答
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;
}

请注意,只有在检查了[[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"); }
© www.soinside.com 2019 - 2024. All rights reserved.