搜索集合

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

下面的代码段应该按文档的标题通过通用排序例程进行搜索,但我不确定是否执行此操作。有帮助吗?

public Document searchByTitle (String aTitle)
{
  foreach(Document doc in this)
  {
    if (doc.Title == aTitle)
    {
      return doc;
    }
    else
    {
      return null;
    }
  }
}
c# collections generic-collections
1个回答
2
投票

否,您的代码在[[不正确中,应为

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

© www.soinside.com 2019 - 2024. All rights reserved.