【问题标题】:Searching through a collection [closed]搜索集合[关闭]
【发布时间】:2019-12-27 13:47:21
【问题描述】:

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

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

2.这段代码 sn-p 应该显示一个方法返回一个集合中存储的书籍数量。这有意义吗?

public static int NoofBooks()
{
  int count = 0;
  foreach(Document doc in this)
  {
   if (doc.Type == "Book")
   {
     count++;
   }
   return count;    
  }
}

【问题讨论】:

  • 你在寻找 Linq 吗? public Document searchByTitle (String aTitle) => this.FirstOrDefault(doc => doc.Title == aTitle);
  • @DmitryBychenko 不不,应该很简单
  • I am not sure whether it does this or not. 你做过什么测试?这是一个简单的调试问题,如果你调试过就会发现。

标签: c# search collections return generic-collections


【解决方案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);
}

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

【讨论】:

  • 请不要屈服于这种行为; op 应该在新帖子上询问新问题(我们可以复制),而不是添加更多不相关的细节。
猜你喜欢
  • 1970-01-01
  • 2016-02-12
  • 2014-12-24
  • 2014-07-31
  • 2015-03-09
  • 2023-01-25
  • 1970-01-01
  • 2020-02-15
  • 2019-03-10
相关资源
最近更新 更多