In this lecture, we will continue the implementation of the CookiesCookbookApp. 1
One of the challenges will be finding an item in a collection by one of its properties. 2
Let's now implement reading the list of ingredients from the user. 3
Let's review how this method is supposed to work. In a loop 4
the user will select IDs of ingredients. 5
If anything other than a valid ID is entered, the loop stops and we consider the recipe finished. 6
Let's start by writing the draft of this loop. 7
It looks like many loops we have written before. 8
There is a flag deciding whether the loop should stop or not. 9
Here is the list of ingredients to which we will add any ingredient the user selected and which will finally 10
be returned as the method's result. 11
The next step is to read the user's input and parse it to an int. 12
If the user input is not parsable to an int, we should stop the execution of the loop. 13
If it is, we should find the ingredient with the matching ID 14
if one exists. The class that stores all the ingredients is the IngredientsRegistry. 15
So I think it is logical to add a method finding an ingredient by its ID to this class. 16
We'll think about the implementation in a second. 17
But first, let's think about what should happen if the user enters a number that does not match any 18
ingredients ID. 19
I think in this case this method should return 20
null. 21
This means we should check here if the selected ingredient is not null and only in this case add to 22
the list of ingredients. 23
Great. 24
Now let's implement the GetById method. 25
The simplest way to implement this method is to iterate the collection of all ingredients and return 26
the one with the matching ID. 27
If no ingredient is found, we will return null. 28
All right, this will work. 29
And I think it is good enough for now. 30
Perhaps it's not the optimal solution. 31
We could, for example, remember the ingredient matching a given ID after it was found for the first 32
time. 33
But for this we would need another collection type called a dictionary and we'll learn about it later. 34
So let's leave it as it is. 35
Let's now uncomment the code that uses selected ingredients to create a new recipe. 36
Firstly, let's adjust this line. 37
Ingredients collection is an IEnumerable. 38
So we must use the Count method, not the Count property. 39
I can see we have a typo here. 40
I will also comment out the method writing the recipes into a file. 41
Let's see if the recipe will be printed to the console. 42
Great. 43
It seems to be working. 44
Let's move on to the next lecture where we will start dealing with writing to and reading from a text 45
file.