【发布时间】: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