1

I have declared a string array and I want to compare with name given by user,

string[] MasterList = new string[] {
  "Askay", "Puram", "Raman", "Srinivasa",
  "Gopal", "Rajesh", "Anju", "Nagara",
};

string YourName;
Console.WriteLine("Enter your name: ");
YourName = Console.ReadLine();

for(i=0; i<5; i++)
{
    a = String.Compare(MasterList[i], YourName);
    Console.WriteLine("Your name is not among the list")
}

The resulting output is not what I am expecting, any ideas how I can go about it?

2
  • 2
    Why use i<5 when you have more than 5 indices in your array? Why not MasterList.Length? Commented Jul 6, 2017 at 14:24
  • Your code doesn't compile and you havent told what you expect. But simple: if(!MasterList.Contains(YourName)){...} instead of the for-loop. Commented Jul 6, 2017 at 14:25

3 Answers 3

2

Why not Contains?

  string[] MasterList = new string[] {
    "Askay", "Puram", "Raman", "Srinivasa",
    "Gopal", "Rajesh", "Anju", "Nagara",
  };

  Console.WriteLine("Enter your name: ");
  string YourName = Console.ReadLine();

  // StringComparer.OrdinalIgnoreCase if you want to ignore case
  // MasterList.Contains(YourName) if you want case sensitive 
  if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
    Console.WriteLine("Your name is not among the list")
Sign up to request clarification or add additional context in comments.

Comments

2

Why not use the Contains method?

Add the following line to your using directives first:

using System.Linq;

And then, remove the for loop and use the following line instead:

if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Your name is not among the list")
}

1 Comment

I think using Contains here is not safe, even it Contains, still may not be the name, should be fully matched
-1
bool found = false;
foreach (string s in MasterList)
{
    if(s == YourName)
    found = true;
}
if(found)
    Console.WriteLine("Your name is among the list");
else
    Console.WriteLine("Your name is not among the list");

8 Comments

Can people who are downvoting please give some comments to @Peter who is a relatively new user :)
@garfbradaz if Peter cannot work out what is wrong with his answer there is always How to write a good answer
Comparing strings with == operators can yield unpredictable results (I did not downvote). You're referencing to see if it's the exact same object (which strings often are not, regardless of contents).
Thanks man...it worked just as i wanted it! thanks @Peter Meadley
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.