C
C#2mo ago
Greya

✅ struggling with basic dictionary and lists....

im practicing on projects by making a libary system i basically have a list of users. i want to assign each user a bunch of books , so ive made an empty list for each user to act as the key for the dictionary. i want it so when i type the user name it acts as the key to the dictionary and allow me to add a book to the string list in the dictionary. but im struggling to put it all together The lists im using have are shown in the SS, and the relevant section im working on is also shown
No description
No description
4 Replies
Pobiega
Pobiega2mo ago
You're on the right track! Not a bad idea to use a dictionary either, that can certainly work there are a few ways you can access a value when you know the key the most obvious one is by just indexing: UsersBooks[username] that will however result in errors if there was no match so when the key is given by a user, I prefer to use .TryGetValue instead
Console.WriteLine("Enter the username: ");
var username = Console.ReadLine()!;

if (userBooks.TryGetValue(username, out var listForUser))
{
// User exists, listForUser is the list in the dictionary
}
else
{
// User does not exist, should we create a new list, or tell the user?
}
Console.WriteLine("Enter the username: ");
var username = Console.ReadLine()!;

if (userBooks.TryGetValue(username, out var listForUser))
{
// User exists, listForUser is the list in the dictionary
}
else
{
// User does not exist, should we create a new list, or tell the user?
}
Greya
Greya2mo ago
I’ll give this a try thanks !
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX2mo ago
If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server