How to remove the input string from the list? [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Here is my code.The first and third points of the program work properly, but the second does not.
If you press the "2" key, the data from the text should be transferred to the list, and the entered line should be deleted in the list,but for reasons I do not understand, the program crashes when entering a value into a string.
using System;
using System.IO;
using System.Collections;
using System.Linq;
using System.Text;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String line;
List<String> list = new List<String>();
String writePath = #"C:\Work\X\hta.txt";
for (; ; )
{
Console.WriteLine("1.Add An Employee");
Console.WriteLine("2.Delete An Employee");
Console.WriteLine("3.Save Database");
Console.WriteLine("4.Exit");
int choice = Convert.ToInt32(Console.ReadLine());
if (choice == 4)
{
break;
}
switch (choice)
{
case 1:
for (; ; )
{
Console.WriteLine("1.Add A Manager");
Console.WriteLine("2.Add An Engineer");
Console.WriteLine("3.Exit");
int choice1 = Convert.ToInt32(Console.ReadLine());
if (choice1 == 3)
{
break;
}
switch (choice)
{
case 1:
line = Console.ReadLine();
list.Add(line);
break;
case 2:
line = Console.ReadLine();
list.Add(line);
break;
}
}
break;
case 2:
list.Clear();
using (StreamReader sr = new StreamReader(writePath))
{
while (!sr.EndOfStream)
{
list.Add(sr.ReadLine());
}
}
foreach(var item1 in list)
{
String linex = Console.ReadLine();
if (item1.Equals(linex))
{
list.Remove(linex);
}
}
break;
case 3:
Console.WriteLine("Do you want to continue?");
String x = Console.ReadLine();
if (x.Equals("yes")){
using (StreamWriter sw = new StreamWriter(writePath))
{
foreach (var item in list)
{
sw.WriteLine(item);
}
}
}
else
{
break;
}
break;
}
Console.ReadLine();
}
}
}
}

In this loop:
foreach(var item1 in list)
{
String linex = Console.ReadLine();
if (item1.Equals(linex))
{
list.Remove(linex);
}
}
You are reading input from the console for every item in the list. This would possibly look like a crash or not quite infinite loop as it's probably not what you're expecting. Instead you should read the input once then loop around the list. However, you should note that if you remove an item from the list while looping through it, you may also get strange behavior. Try just removing the string without the loop:
String linex = Console.ReadLine();
if (list.Contains(linex))
{
list.Remove(linex);
}

may be you writePath of value [C:\Work\X\hta.txt] file do not exists,so you should create an empty text file on you disk.

Related

C# if function criteria are fulfilled but not running linked code

I'm trying to finish a project, but the conditions I set in the if statement are fulfilled and not running the linked code. basically, I type null and it keeps running, even though it should set running to false, and it doesn't print the answer at the bottom. it's supposed to be a random number generator with variables linked to each number. I'm still new to C#, So I'm probably just using things wrong, as usual.
edit: added some fixes. also the line at the end, Console.WriteLine(answer) on line 99, is being considered unreachable, and it is the main way for me to know if my code works. if someone could let me know how to fix that, it would be great. also, could someone tell me some alternatives to the goto statement? edit 2: thanks for the help, It works now.
using System.Collections;
internal class Program
{
private static void Main(string[] args)
{
string item1;
string item2;
string item3;
string item4;
string item5;
string answer;
item1 = "";
item2 = "";
item3 = "";
item4 = "";
item5 = "";
answer = "";
bool Running = true;
while (Running)
{
Console.Write("Enter item 1: ");
item1 = Console.ReadLine();
Console.WriteLine("Enter item 2: ");
item2 = Console.ReadLine();
Console.WriteLine("Enter item 3, or type null: ");
item3 = Console.ReadLine();
if (item3 == "null" )
{
Running = false;
item3 = "";
}
Console.WriteLine("Enter item 4, or type null: ");
item4 = Console.ReadLine();
if (item4 == "null")
{
Running = false;
item4 = "";
}
Console.WriteLine("Enter item 5: ");
item5 = Console.ReadLine();
if (item5 == "null")
{
Running = false;
item5 = "";
}
}
reroll:
Random random = new Random();
switch (random.Next(1, 6))
{
case 1:
{
answer = item1;
break;
}
case 2:
{
answer = item2;
break ;
}
case 3:
{
if (item3 == "")
{
goto reroll;
}
answer = item3;
break;
}
case 4:
{
if (item4 == "")
{
goto reroll;
}
answer = item4;
break;
}
case 5:
{
if (item5 == "")
{
goto reroll;
}
answer = item5;
break;
}
Console.WriteLine(answer);
}
}
}
As far as your code is concerned I have several issues to bring up
When you feel the need to define variables like item1, item2, item3, etc then it is time to consider arrays and collections. You are learning bad habits otherwise. A fixed size array string[] items would suffice here, although a better solution would be to use a variable size List<string> items.
Try to divide up your code into functional parts, and use functions in order to minimize any possible side effects. This way you control the flow of information better.
If it all possible avoid goto, unless you absolutely need to. It makes code much harder to trace out and bugs are harder to catch. Alternatively use either a fixed count iteration like a for() loop, or a general while() statement and use the keyword break to exit the loop (or continue to move to the next iteration).
A lot of other smaller issues are a matter of experience with programming.
The way I read the code you are trying to do something like this
Enter Item 1
aaa
Enter Item 2
bbb
Enter Item 3
ccc
Enter Item 4 or press [ENTER] or type null to end.
ddd
Enter Item 5 or press [ENTER] or type null to end.
null
User List:
aaa
bbb
ccc
ddd
Randomly Selected Item: ddd
Here is one way of getting there using the principles laid out above. The code below is intended for learning purposes, with the hope that you are going to be able to follow along and understand what does what.
class Program
{
static readonly Random rng = new Random();
static void Main(string[] args)
{
// Get user inputs
string[] items = AskItemsFromUser(minItems:3, maxItems:5);
// Show what was entered as a list
Console.WriteLine("User List:");
Console.WriteLine(string.Join(Environment.NewLine, items));
Console.WriteLine();
// Show random item from list
string item = PickRandom(items);
Console.WriteLine($"Randomly Selected Item: {item}");
}
public static string[] AskItemsFromUser(int minItems, int maxItems)
{
List<string> items = new List<string>();
while (items.Count < maxItems)
{
// Change the prompt depending on the number of items entered.
if (items.Count >= minItems)
{
Console.WriteLine($"Enter Item {items.Count + 1} or press [ENTER] or type null to end.");
}
else
{
Console.WriteLine($"Enter Item {items.Count + 1}");
}
// get user input
string input = Console.ReadLine();
// if input=="null" or an empty string
if (input.Equals(string.Empty) || input.Equals("null"))
{
// and min # of items already reached
if (items.Count >= minItems)
{
// the exit loop
break;
}
}
else
{
// add user input to list
items.Add(input);
}
}
Console.WriteLine();
return items.ToArray();
}
public static string PickRandom(params string[] items)
{
// Use a random number generator to pick an item
// index = 0..count-1
int index = rng.Next(0, items.Length);
return items[index];
}
}

Compare 1st then 2nd then 3rd column of Text File

I'm making a Quizlet Type program and need help comparing text files. I have written
Hello, Hallo
Dog, Hund
Cat, Katze
That is my Text file. I want my program to compare 1st column
Hello, Hallo
And then after that comparison
Dog, Hund
and after that
Cat, Katze
As you see here I wrote code that compares the first row to the second row. But after that, it just doesn't compare to the second column of the file. I need help comparing to 2nd column then 3rd etc.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test32
{
class Program
{
static void Main(string[] args)
{
string filepath = #"C:\Users\akred\Desktop\testfall2\testfall2\Eng.txt";
bool wantstoguess = true;
int attempt = 0;
bool win = false;
int row = 0;
List<engword> word = new List<engword>();
List<string> lines = File.ReadAllLines(filepath).ToList();
foreach (var line in lines)
{
string[] entries = line.Split(',');
engword newWord = new engword();
//Ew = Englisches Wort
//REw = Richtig Englisches Wort bzw richtige übersetzung
newWord.Ew = entries[0].Trim();
newWord.REw = entries[1].Trim();
word.Add(newWord);
}
foreach (var engword in word)
{
do
{
do
{
Console.WriteLine("What is " + $"{engword.Ew }" + " in English");
attempt++;
string guessed = Console.ReadLine();
try
{
if (guessed == $"{ engword.REw }")
{
Console.WriteLine("Correct");
win = true;
++row;
}
else if ($"{ engword.REw }" != guessed)
{
Console.WriteLine("Incorrect");
}
}
catch
{
Console.WriteLine("Please Write a word");
}
} while (win == false);
if (win == true)
{
Console.WriteLine("You gave guessed it!");
Console.Write("It took you " + attempt + " attempts!");
Console.ReadLine();
}
Console.Write("Do you want to continue? [Yes/No]?");
string answer = Console.ReadLine();
if (answer == "Yes")
wantstoguess = true;
win = false;
if (answer == "No")
wantstoguess = false;
} while (wantstoguess == true);
}
Console.ReadLine();
}
}
}
It seems, that you are looking for a Dictionary, Dictionary<string, string>, e.g.
using System.Linq;
...
Dictionary<string, string> EnToDe = File
.ReadLines(filepath)
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(line => line.Split(','))
.ToDictionary(pair => pair[0].Trim(),
pair => pair[1].Trim(),
StringComparer.OrdinalIgnoreCase);
You can easily create reversed German - English dictionary as well:
Dictionary<string, string> DeToEn = EnToDe
.ToDictionary(pair => pair.Value,
pair => pair.Key,
StringComparer.OrdinalIgnoreCase);
Now you can easily get words
List<string> englishWords = EnToDe.Keys.ToList();
List<string> deutschWords = EnToDe.Keys.ToList();
and translation
string english = "CAT";
if (EnToDe.TryGetValue(english, out var deutsch))
Console.Write($"English \"{english}\" is German \"{deutsch}\"");
else
Console.Write($"Sorry, Engish \"{english}\" is not found in the dictionary");
Edit: If you want to implement some kind of test where student must translate each word from German into English, you can try a simple loop. First we prepare the words:
string[] germanWords = DeToEn
.Keys
.OrderBy(x => Guid.NewGuid()) // Shuffle
.ToArray();
// words which are difficult to learn and thus should be tested again
HashSet<string> wordsToRepeat = new HashSet<string>();
Then loop over these words:
foreach (string word in germanWords) {
int attempt = 0;
while (true) {
attempt += 1;
Console.WriteLine($"What is {word} in English?");
string guessed = Console.ReadLine().Trim();
if (string.Equals(guessed, DeToEn[word], StringComparison.OrdinalIgnoreCase)) {
Console.WriteLine("You gave guessed it!");
Console.WriteLine($"It took you {attempt} attempts!");
break;
}
Console.WriteLine("Incorrect");
// If the word is too difficult to translate, it should appear again
if (attempt >= 3) // let word be difficult if it takes 3+ attempt to guess it
wordsToRepeat.Add($"{word},{DeToEn[word]}");
}
Console.Write("Do you want to continue? [Yes/No]?");
string answer = Console.ReadLine().Trim();
if (string.Equals(answer, "N", StringComparison.OrdinalIgnoreCase) ||
string.Equals(answer, "NO", StringComparison.OrdinalIgnoreCase))
break;
}
File.WriteAllLines("c:\WordsToRepeat.txt", wordsToRepeat);
The way your code is structured is a bit confusing, but if you see what it is actually doing it will be
for each word
{
until the user opts out
{
until the answer is correct
{
try to guess
}
}
}
Which means you never get to the next word unless the user says they don't want to continue. A better way would be do something like
for each word
{
until the answer is correct
{
try to guess
}
if(does not want to continue)
break;
}
Here break will get you out of the for each word loop
UPDATE
If I understood correctly what you're trying to achieve, you should end up with something like
foreach (var engword in word)
{
// do --> remove this
// {--> remove this
do
{
...
} while (win == false);
if (win == true)//this check is unnessesary, you won't get here unless win is true
{
Console.WriteLine("You gave guessed it!");
Console.Write("It took you " + attempt + " attempts!");
Console.ReadLine();
}
Console.Write("Do you want to continue? [Yes/No]?");
string answer = Console.ReadLine();
//Add this
if (answer == "No")
{
Console.Write("Okay, bye!");
break;
}
win = false;
// if (answer == "No")--> remove this
// wantstoguess = false;--> remove this
//} while (wantstoguess == true); --> remove this
}
You should use Dictionary<string, string> instead of List. Then key of dictionary will be english word and value will be german word.
After you build dictionary from txt file you have to loop the dictionary keys (english words) and you have to compare user's input with dictionary value of current key.
// firstly you have to build dictionary similar this
string filepath = #"C:\Users\akred\Desktop\testfall2\testfall2\Eng.txt";
Dictionary<string, string> myDict = File
.ReadLines(filepath)
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(line => line.Split(','))
.ToDictionary(words => words[0].Trim(), words => words[1].Trim());
foreach(var item in myDict)
{
// here you have to implement loop for user's input and comparing with value
Console.WriteLine($"What is { item.key } in english?");
string guessed = Console.ReadLine();
if (guessed == item.value)
{
// OK
}
else
{
// fail
}
}

How can I escape from this loop?

I am a beginner at coding - I just started a week ago. I am trying to develop a program where the user can either see all of the names in a list or add a name to a list. When the user prompts to see the names in the list, and then decides to take another action, they are stuck in an endless loop where they can only see the names again. I want them to be able to go back to the start and choose to either see the names or add a name.
I've tried reorganizing and looking things up, but I'm still at a loss.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> names = new List<string>();
names.Add("Vasti");
names.Add("Cameron");
names.Add("Ezra");
names.Add("Tilly");
bool program = false;
bool program2 = false;
Console.WriteLine("Welcome to the names lost! If you wish to add
a name to the list, type 1. If you want to see current names in
the list,
type 2.");
string userChoice = Console.ReadLine();
do
{
switch (userChoice)
{
case "1":
Console.WriteLine("Add a name to the squad.");
string userAddName = Console.ReadLine();
names.Add(userAddName);
break;
case "2":
Console.WriteLine("Here's the list:");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Wanna do that again? Type yes or
no.");
do
{
string userContinue = Console.ReadLine();
switch (userContinue)
{
case "yes":
program = true;
program2 = false;
break;
case "Yes":
program = true;
program2 = false;
break;
case "no":
program = false;
program2 = false;
break;
case "No":
program = false;
program2 = false;
break;
default:
Console.WriteLine("Please enter either
yes or no");
userContinue = Console.ReadLine();
program2 = true;
break;
}
}
while (program2 == true);
break;
default:
Console.WriteLine("Please type either 1 or 2 to
select an option.");
break;
}
}
while (program == true);
}
}
I expect the user to return to the beginning prompt, but they are stuck in the same prompt over and over. There are no error messages.
Two major things to cover your difficulties.
First, the input hint should be in the loop so it can show when each loop begin.
Second, do while loop decide if the loop should continue at the end and in your design; it depends on what user input which should be directly utilized as while condition.
Therefore, your code could be simplified as
public static void Main()
{
List<string> names = new List<string>() { "Vasti", "Cameron", "Ezra", "Tilly" };
string userChoice = "";
do
{
Console.WriteLine($#"Welcome to the names lost!{Environment.NewLine} If you wish to add a name to the list, type 1.{Environment.NewLine} If you want to see current names in the list, type 2.");
userChoice = Console.ReadLine();
switch (userChoice)
{
case "1":
Console.WriteLine("Add a name to the squad.");
string userAddName = Console.ReadLine();
names.Add(userAddName);
break;
case "2":
Console.WriteLine("Here's the list:");
foreach (string name in names)
{
Console.WriteLine(name);
}
break;
default:
Console.WriteLine("Please type either 1 or 2 to select an option.");
break;
}
Console.WriteLine(#"Wanna do that again? Type yes or no.");
userChoice = Console.ReadLine();
}
while (userChoice.Equals("yes", StringComparison.OrdinalIgnoreCase));
Console.WriteLine("Program finished");
Console.ReadLine();
}
Change the do{}while() loops to regular while(){} loops.Move string userChoice = Cosole.ReadLine(); inside of the top while loop or you will never ask for other options. . . Also set the ((bool program=true; and bool program=true;)) at the beginning. Do{}while() loops do everything inside the {} first then check to see if the while statement is still true.

Console application, How do I make Console.ReadLine() IF/ELSE Statements? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was making a tool named "Ferna".. And I was trying to make different commands on it, but the problem is that these "commands" have to be in order, like when I try to execute a command, I have to execute them in order.. But I want it like it doesn't have to be in order so if i write "cyan" it executes it, it doesn't have to wait for the 5th ReadLine()
Here's my code:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
if (Console.ReadLine() == "cmds")
{
Console.WriteLine(cmds);
}
else if (Console.ReadLine() == "calculator")
{
cal.ShowDialog();
}
else if (Console.ReadLine() == "cyan")
{
Console.ForegroundColor = ConsoleColor.Cyan;
}
else if (Console.ReadLine() == "black")
{
Console.ForegroundColor = ConsoleColor.Black;
}
else if (Console.ReadLine() == "clear")
{
Console.Clear();
}
}
}
}
Store the results of your Console.ReadLine statement in a variable. This way you don't have to keep calling Console.ReadLine.
var cmd = Console.ReadLine();
if (cmd == "cmds")
{
Console.WriteLine(cmds);
}
else if (cmd == "calculator")
{
...
The issue is essentially every time the if checks each condition its going to wait for more input
Update :
You will need to put it in a loop
string cmd = "";
while(cmd != "exit")
{
cmd = Console.ReadLine();
if (cmd == "cmds")
{
Console.WriteLine(cmds);
}
else if (cmd == "calculator")
{
...
}
Here is the good old switch statement. Gotta break it out every once in while! If/Else works just as well though. This will loop and check for the next line.
class Program
{
static void Main(string[] args)
{
while((string command = Console.ReadLine()) != null)
{
switch (command.ToUpper())
{
case "CMD":
Console.WriteLine("CMD");
break;
case "CALCULATOR":
cal.ShowDialog();
break;
default:
Console.WriteLine("Default");
break;
}
}
}
}
Using Queue<string> to keep a list of commands might not be a bad idea:
class Program
{
static Queue<string> commandQueue = new Queue<string>(new[] {"FirstCommand", "SecondCommand", "ThirdCommand"});
static void Main(string[] args)
{
using (Queue<string>.Enumerator enumerator = commandQueue.GetEnumerator())
{
while (enumerator.MoveNext())
{
Console.WriteLine("Type in next command or type exit to close application");
//this while is used to let user make as many mistakes as he/she wants.
while (true)
{
string command = Console.ReadLine();
if (command == "exit")
{
Environment.Exit(0);
}
//if typed command equals current command in queue ExecuteCommand and move queue to next one
if (command == enumerator.Current)
{
ExecuteCommand(command);
break;
}
else//Show error message
{
if (commandQueue.Contains(command))
{
Console.WriteLine("Wrong command.");
}
else
{
Console.WriteLine("Command not found.");
}
}
}
}
Console.WriteLine("We are done here, press enter to exit.");
Console.ReadLine();
}
}
//Method that executes command according to its name
static void ExecuteCommand(string commandName)
{
switch (commandName)
{
case "FirstCommand":
Console.WriteLine("FirstCommand executed");
break;
case "SecondCommand":
Console.WriteLine("SecondCommand executed");
break;
case "ThirdCommand":
Console.WriteLine("ThirdCommand executed");
break;
default:
Console.WriteLine("Command not found");
break;
}
}
}
Also if the requirement states that actions should performed in exact order it might not be a bad idea to just let the user press Enter to execute the next command instead of having to type its name.

Loop through list, match word call description from list

I am having a problem constructing a loop WHICH will COMPARE a VAR(userSelection) against the name ITEMS in my LIST(Listings). The goal is that if userSelection MATCHES name, getDescription will Console.WriteLine the GetDefinition and display the definition of the word in the list matched. Most of my code is working, and i've been working on this assignment for a week.
I'm very much a newb, please assume I know nothing. All help is appreciated. I think this would be a while loop, but i've played with all the loops now and am lost and confused. I'm a newb, please use small words and be as detailed as you can afford to be. It's greatly appreciated. Thank you.
My C# Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;// Needed for Streaming...
using System.IO;// Needed for Streaming...
namespace a090___StreamReader_DictionarySearch
{
class Program
{
private const String FILE_NAME = "dictionary.txt";//establish text file instance
public void Play()
{
do
{
DisplayTitle();
List<Listing> items = LoadListings();//create a list of WordDef objects
Console.Write(string.Join(" | ", items.Select(x => x.GetName()))); //Console.Write("\b \b");// Backspace would also of worked
DisplayText("\n\nPlease enter a word from the selections about to see it's definition");// Nice use of PROMPT
String userSelection = Console.ReadLine().ToLower();//Capture input
//loop through all of the listings, and compare each one to userSelection
//Then once it equals print definition
bool found = false;
foreach (Listing item in items)
{
if (userSelection == item.GetName())
{
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + item.GetDefinition());
found = true;
break;
}
}
if (!found)
{ Console.WriteLine("I'm sorry, I don't have a match for that."); }
} while (PlayAgain());
Salutation();
}
//ToolBox -- my program specific tools
public List<Listing> LoadListings()//load entries display as list
{
StreamReader fileIn = new StreamReader(FILE_NAME);
List<Listing> entry = new List<Listing>();
//loop through every line of the file
while (!fileIn.EndOfStream)
{
String line = fileIn.ReadLine();
String[] pieces = line.Split(':');
if (pieces.Length < 1) continue;//error handling - set to length of text items
Listing myListing = new Listing(pieces[0], pieces[1]);
entry.Add(myListing);
}
fileIn.Close(); return entry;
}
//MaxBox -- my useful tools
public void DisplayText(String StringNameIs)
{ Console.WriteLine(StringNameIs); }//Where are we?
public Boolean PlayAgain()
{
Console.Write("\n\nDo you select again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower();
if (command == "y" || command == "yes") return true;
return false;
}
public void Salutation()
{ Console.Clear(); Console.WriteLine("Ti Do - oh - oh Ti Do -- So Do!"); } //The last line from the 'do-re-mi' song from the Sound of Music
public void DisplayTitle()
{ Console.Clear(); Console.WriteLine(">>>-- A Dictionary of Sounds --<<< \n"); } //Announce Our Program
static void Main(string[] args)
{
Program DictionaryLookup = new Program();
DictionaryLookup.Play();
Console.Read();
}
}
}
My Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace a090___StreamReader_DictionarySearch
{
class Listing
{
private String name;
private String definition;
public Listing(String name, String definition)
{ this.name = name;
this.definition = definition;}
public String GetName() {return name;}
public String GetDefinition() {return definition; }
}
}
My Text File
Doe: a deer, a female deer
Ray: a drop of golden sun
Me: a name I call myself
Far: a long, long way to run
Sew: a needle pulling thread
La: a note to follow Sew
Tea: a drink with jam and bread
This is untested, but should work, using your existing code.
Assuming each "name" (doe, ray, etc) only occurs once (which they do), then you can use Linq's "SingleOrDefault", which will return null if no match is found.
var selection = items.SingleOrDefault(x => x.GetName() == userSelection);
if (selection == null)
Console.WriteLine("I'm sorry, I don't have a match for that.");
else
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + selection.GetDefinition());
To ignore case during comparison, try modifying the above:
... items.SingleOrDefault(x => String.Compare(x.GetName(), userSelection, true));
There are a number of other things you could change here, but perhaps it won't matter for your assignment. For example, I'd eliminate the private variables in your Listing class and change the public "get" methods into properties:
public String Name { get; private set; }
public String Definition { get; private set; }
Substitute the code
while (true)
{
if (userSelection == name)
{Console.WriteLine("You selected: " + Listing.userSelection() +
"\nWhich Means: " + Listing.items.GetDefinition());}
}
else { Console.WriteLine("I'm sorry, I don't have a match for that."); }
with this
bool found = false;
foreach (Listing item in items)
{
if (userSelection == item.GetName().ToLower())
{
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + item.GetDefinition());
found = true;
break;
}
}
if (!found)
{ Console.WriteLine("I'm sorry, I don't have a match for that."); }
I have use the foreach statement; with this statement you can iterate all items of your collection.
Inside the foreach loop I check if the element Name is equal with the user input, if match I set a bool variable indicating element found.
After the loop if element not found print the message.
NB Obviously this code can be written more concisely with LINQ.

Categories