Dome332
Dome332

Reputation: 1

How to loop trough dictionary and check if the ReadLine input is equal to the Dictionary Key

int userInput = Convert.ToInt32(Console.ReadLine());
            foreach (KeyValuePair<int,Library> lib in dictionary)
            {
                if (userInput == lib.Key)
                {
                    Console.WriteLine("You chose book = {0}",lib.Value.bookName);
                }
                else
                {
                    Console.WriteLine("Wrong Input");
                }
            }

Hello i am stuck at figuring out how i can check equality userInput(ReadLine) to a Key in Dictionary without else command spamming "Wrong Input" while looping trough Dictionary.

Upvotes: 0

Views: 451

Answers (5)

Matt
Matt

Reputation: 1757

Similar to the Linq implementation by Nasar, you could use the TryGetValue method on dictionary (Docs).

The good thing about using TryGetValue is you only iterate the dictionary once to do 2 things.

  1. Check if the value exists
  2. Get the value from the dictionary
int userInput = Convert.ToInt32(Console.ReadLine());

if (dictionary.TryGetValue(userInput, out Library library))
    Console.WriteLine($"You chose book = {library.bookName}");
else
    Console.WriteLine("Wrong Input");

TryGetValue will return true if the record is found and false otherwise.

Upvotes: 2

Nasar Eddaoui
Nasar Eddaoui

Reputation: 81

You could utilize LinQ for this and shorten the code making it simple and easy to read. is would spend more time trying to validate the input from the user and make sure that the imputed value is a digit and nothing else.

 int userInput = Convert.ToInt32(Console.ReadLine());
    var result = dictionary.FirstOrDefault(x => x.Key == userInput);
    if(result.Value != null)
        Console.WriteLine("You chose book = {0}", result.Value);
    else
        Console.WriteLine("Wrong Input");

An alternative way would also to run a Boolean expression validating if the key exist before executing the fetch value.

        int userInput = Convert.ToInt32(Console.ReadLine());
        var result = dictionary.ContainsKey(userInput);

        if(!result)
            Console.WriteLine("Wrong Input");
        else
        {
            var book = dictionary.FirstOrDefault(x => x.Key == userInput);
            Console.WriteLine("You chose book = {0}", book.Value);
        }

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56433

Currently your code is essentially saying "for each key in the dictionary that is not equal to the one the user has entered then print wrong input.." which is clearly not what you want.

instead you want something along the lines of:

"iterate through the entire dictionary and if every single key is not equal to the one the user has entered then print wrong input..."

in order to achieve that:

  1. you don't need an else block within the loop.
  2. use a simple boolean variable that will tell you whether a match has been found or not during the iteration and then after the loop check the state of the boolean and then print "wrong input" if necessary.

Example:

bool wrongInput = true;
int userInput = Convert.ToInt32(Console.ReadLine());
foreach (KeyValuePair<int,Library> lib in dictionary)
{
     if (userInput == lib.Key)
     {
           Console.WriteLine($"You chose book = {lib.Value.bookName}");
           wrongInput = false;
           break; // exit early as there's no need to continue the iterating.
     }
}

if (wrongInput) Console.WriteLine("Wrong Input");

Note that I've corrected your code for completeness but I would not recommend following the above approach i.e. iterating over a dictionary, instead look into ContainsKey instead of looping over the dictionary.... as it's the idiomatic, less code, more readable etc...

Upvotes: 0

user3434255
user3434255

Reputation:

Seems like there is a method ContainsKey in the .Net lib.

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.containskey?view=netframework-4.8

You can simply call this and removed the whole loop.

Upvotes: 2

Paulo44
Paulo44

Reputation: 211

Try a boolean to verify

int userInput = Convert.ToInt32(Console.ReadLine());
bool exists= false;
            foreach (KeyValuePair<int,Library> lib in dictionary)
            {
                if (userInput == lib.Key)
                {
                    Console.WriteLine("You chose book = {0}",lib.Value.bookName);
                    exists = true;
                }
            }
            if(!exists){
                  Console.WriteLine("Wrong Input");
            }

Upvotes: 1

Related Questions