另一种解决字典搜索的方法(不使用LINQ)



我想问您LINQ是否是进行字典搜索的最佳方式。

private readonly Dictionary<string, string[]> books = new Dictionary<string, string[]>();

现在我使用的LINQ是这样的:

public List<string> FindAllBooks(string author)
{
    List<string> BooksFound = new List<string>();
    var matchingKeys = books.Where(x => x.Value.Contains(author)).Select(x => x.Key);
    foreach(var item in matchingKeys)
    {
        BooksFound.Add(item);
    }
    return BooksFound;
}

此外,我正在努力使这个代码OOP。如果我的解决方案不好,你能帮我了解如何正确地做到这一点吗?

Linq-only解决方案如下:

public List<string> FindAllBooks(string author) => books
  .Where(book => book.Value.Contains(author))
  .Select(book => book.Key) 
  .ToList();  

没有Linq解决方案(循环仅(可以是

public List<string> FindAllBooks(string author) {
  List<string> BooksFound = new List<string>();
  foreach (var book in books)
    if (book.Value.Contains(author))
      BooksFound.Add(book.Key);
      
  return BooksFound; 
}

您的代码(还不错(介于(Linq和loop(之间。books字典Key是某种Id(它是ISBN吗?(这就是为什么必须扫描整个字典的原因。你想在Linq循环的帮助下完成它吗?或者它们的混合是品味、可读性等问题。

最新更新