I would like to use my variable i
(that is used to sequence a loop) to name a record. This in order to know both how many of these records I have and to be able to loop through each one in a for
loop.
This is how I have tried to do it:
while (UserValue != "none")
{
Console.WriteLine("Input a product Name or type \"none\" to exit.");
UserValue = Console.ReadLine();
if (UserValue == "none")
break;
Console.WriteLine("Input this products value in Pounds.");
products i = new(UserValue, float.Parse(Console.ReadLine()));
i = i 1;
}
I'm not even sure if it is possible so if it isn't, any alternative solution would be greatly appreciated.
CodePudding user response:
It seems, that you want a collection, say List<T>
of items, e.g.
//TODO: decimal is better if "value" stands for money
// I used named tuple here, but you may want an elaborated custom class
var products = new List<(string name, float value)>();
// Keep asking user to input products until "none" is given
while (true) {
Console.WriteLine("Input a product Name or type \"none\" to exit.");
UserValue = Console.ReadLine();
//TODO: trim spaces and, probably, use case insensitive check
if (UserValue == "none")
break;
Console.WriteLine("Input this products value in Pounds.");
//TODO: float.TryParse is a better option
products.Add((UserValue, float.Parse(Console.ReadLine())));
}
then having collection you can loop over it:
for (int i = 0; i < products.Count; i) {
(string name, float value) = products[i];
...
}
or
foreach (var (name, value) in products) {
...
}
CodePudding user response:
A better strategy is using a List<products>
. Also, rename the products
class to just product
:
var allProducts = new List<product>();
// ...
Console.WriteLine("Input a product Name or type \"none\" to exit.");
UserValue = Console.ReadLine();
if (UserValue == "none")
break;
Console.WriteLine("Input this product's value in Pounds.");
allProducts.Add(new product(UserValue, float.Parse(Console.ReadLine())));
You can still loop over this allProducts
list with either a for
loop (look at the .Count
property of the list) or a foreach
loop.