【问题标题】:Another way of solving dictionary search (without LINQ)解决字典搜索的另一种方法(没有 LINQ)
【发布时间】:2022-01-02 16:02:19
【问题描述】:

我想问一下,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,则希望 l 可以执行 foreach 循环。逻辑保持不变。
  • “最佳”是主观的,取决于您的目标和其他因素,例如您存储的数据集的大小。例如,如果您的字典包含 1 亿个条目,这绝对不是最好的方法。如果你想让你的代码“面向对象”,你应该定义代表书籍的类,而不是处理包含字符串和字符串数组的字典。

标签: c# linq dictionary


【解决方案1】:

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 和循环)。 books 字典 Key 是某种 Id(是 ISBN 吗?)这就是为什么您必须扫描整个字典的原因。你想在 Linqloops 的帮助下完成它还是它们的混合是一个品味、可读性等问题。

【讨论】:

  • 看起来Linq更清晰、更简单。我在某处看到了有效性的比较,Linq 有时会慢一些,但总体上它是否比“无 Linq 方法”更受欢迎?
  • @Tomasz Majek:除非您必须处理数百万个项目,否则重要的不是性能(微秒甚至纳秒)。 Linq 因其灵活性以及易于编写和维护而广受欢迎。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
相关资源
最近更新 更多