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

Time:10-03

When i do it this way it print out "username not found" for each index in the list(name), i want it to only print it once if it doesn't find the username in the entire list(name) without using LINQ

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  ;
                   
            }
    }
  }
}

CodePudding user response:

You can do something like this. Have a variable to identify if the username was found.

        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;
        bool found = false;
        while (a < name.Count)
        {
            if (name[a] == username)
            {
                found = true;
            }
            a  ;
        }
        if (found)
        {
            Console.WriteLine(username   " was found");
        }
        else
        {
            Console.WriteLine(username   " was not found");
        }

CodePudding user response:

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.

  • Related