I would like to ask you if LINQ is the best way to do this dictionary search.
private readonly Dictionary<string, string[]> books = new Dictionary<string, string[]>();
Right now I'm using LINQ like this:
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;
}
Also I'm trying to make this code OOP. If my solution is bad, could you help me understand how to do this properly?
CodePudding user response:
Linq only solution is something like this:
public List<string> FindAllBooks(string author) => books
.Where(book => book.Value.Contains(author))
.Select(book => book.Key)
.ToList();
No Linq solution (loops only) can be
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;
}
Your code (which is not bad) is somewhere in between (both Linq and loop). books
dictionary Key
is some kind of Id
(is it ISBN?) that's why you have to scan the entire dictionary. Would you like to do it with a help of Linq, loops or a mixture of them is a question of taste, readability etc.