我想問您 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。如果我的解決方案不好,你能幫我理解如何正確地做到這一點嗎?
uj5u.com熱心網友回復:
Linq 唯一的解決方案是這樣的:
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 號嗎?)這就是為什么你必須掃描整個字典。你想在Linq的幫助下做到這一點,回圈或它們的混合是品味、可讀性等的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/401751.html
