I have totally understed the lists but I have one more thing that I need to know before I am down with it
I have created to lists one with string and one with int
The first string name is jack and its value is 2 The Second string name is john and its values is 5 But as result I am taking John's value 2 John's value 5
Jack's value 2 Jack's value 5
How to make the first string to have only one value and the second its own
List<string> NameList = new List<string>();
Console.WriteLine("Please insert a name ");
string name = Console.ReadLine();
NameList.Add(name);
List<int> answerList = new List<int>();
Console.WriteLine("Please insert a value");
int x = int.Parse(Console.ReadLine());
answerList.Add(x);
Console.WriteLine("Do you want to calculate more ? (yes/no)");
string answer = Console.ReadLine();
answer.Trim();
bool isYes = true;
while (isYes)
{
if (answer == "yes")
{
Console.WriteLine("Please insert another name/value");
name = Console.ReadLine();
x = int.Parse(Console.ReadLine());
NameList.Add(name);
answerList.Add(x);
Console.WriteLine("Do you want to calculate more ? (yes/no)");
answer = Console.ReadLine();
answer.Trim();
}
else if (answer == "no")
{ break; }
} string are = " are ";
foreach (var NAME in NameList)
foreach (var item in answerList)
Console.WriteLine("The values of " + NAME + are +item);
The problem is here:
foreach (var NAME in NameList)
foreach (var item in answerList)
you are doing a cross join, matching every name in NameList
to every value in answerList
. You have a few options:
Name
and Value
properties and store instances of that class in a single listZip
Linq function to line up the lists element-by-element and iterate through the results in a foreach
Other habits to get into now:
Use consistent, standard capitalization. Use camelCase for variables (e.g. nameList
, answerList
) and PascalCase for properties (Name
, Answer
). Use ALL CAPS for constant values
remember that Trim
returns the trimmed string, so answer.Trim()
does nothing (it throws away the output of Trim
). Use answer = answer.Trim()
instead.