Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#: Check list for search term and print all matching values, or display Not found if no matching values exist

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading