thugcat85
thugcat85

Reputation: 47

C# create a program that searches a list and prints out if the string was found or not

My code below prints out "username not found" for each index in the name list however I only want it to print once if it doesn't find the username in the entire list (without using LINQ).

What's the issue?

using System;
using System.Collections.Generic;

namespace exercise_74
{
    class Program
    {
        public static void Main(string[] args)
        {
            List<string> name = new List<string>();
            while (true)
            {
                string input = Console.ReadLine();
                if (input == "")
                {
                    break;
                }
                name.Add(input);
            }
            Console.WriteLine("who are u looking for ");
            string username = Console.ReadLine();
            int a = 0;
            while (a < name.Count)
            {
                if (name[a] == username)
                {
                    Console.WriteLine(username + " was found");

                }
                else
                {
                    Console.WriteLine(username + " was not found");
                }
                a++;

            }
        }
    }
}

Upvotes: 0

Views: 148

Answers (1)

Victor
Victor

Reputation: 109

var found = false;

while(a < name.Count)
        {
            if(name[a] == username )
            {
                Console.WriteLine(username + " was found");
                found = true;
                break;
                  
            }             
                  
            a++;
               
        }

    if(!found)
         Console.WriteLine(username + " was not found");

Writing on phone so might not be perfect formation.

Upvotes: 1

Related Questions