I’m trying to add a search option to my app. If the user’s search term exists in a list (of strings), all matching elements from that list should be displayed. If not, "Not found" should be displayed. I have the for loop working, but I can’t seem to find where the not found condition should go.
for (int i = 0; i<myList.Count; i++)
{
if (myList[i].Contains(search))
{
WriteLine(myList[i]);
} else
{
WriteLine("not found");
}
}
>Solution :
Since you want to get ALL of the matches, you need to keep a running list of the matches you found. After you have checked all items in your list, you can determine if there was none found by checking how many matches are in your list.
var matches = new List<string>();
for (int i = 0; i < myList.Count; i++)
{
if (myList[i].Contains(search))
{
matches.Add(myList[i]);
}
}
if (matches.Count == 0)
{
WriteLine("not found");
}
else
{
foreach (var match in matches)
{
WriteLine(match);
}
}
If you do not need the matches afterwards, you could replace the list with an int and increment that when you find a match. If a match is found in the loop, write line the match. Then after you’ve checked all items in your list, you can check if your counter equals zero, if so write line "not found".
var counter = 0;
for (int i = 0; i < myList.Count; i++)
{
if (myList[i].Contains(search))
{
WriteLine(myList[i]);
counter++;
}
}
if (counter == 0)
{
WriteLine("not found");
}