2017-07-06 14 views
1

私は文字列の配列を宣言していると私は、ユーザによって与えられた名前と比較したい、文字列配列の値を比較するにはどうすればよいですか?

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") 
} 

結果の出力は、私は、私はそれについて移動する方法を、任意のアイデアを期待していたものではないのですか?

+2

なぜあなたは配列に5つの以上のインデックスを持っているとき、私は5' < 'でしょうか?どうして 'MasterList.Length'? –

+0

あなたのコードはコンパイルされず、あなたが期待していることを話しません。しかし単純です:forループの代わりにif(!MasterList.Contains(YourName)){...} '。 –

答えて

-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"); 
+1

downvotingしている人は、比較的新しいユーザーである@Peterにコメントをしてください:) – garfbradaz

+1

@garfbradazもしPeterが彼の答えに間違いがあってもうまくいかないのであれば、いつでも[良い答えを書く方法](https://stackoverflow.com/help/how-to-answer) – Jamiec

+0

それは私が何を意味するか@Jamiec - それは助けになり、指導のためのリンクを与えました(私はそれを自分自身で投稿しようとしていました) - 工藤! :) – garfbradaz

2

なぜContainsメソッドを使用しないのですか?

最初にあなたのusingディレクティブに次の行を追加します。

using System.Linq; 

をそして、forループを削除し、代わりに次の行を使用します。

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

私は 'Contains'を使ってここでは安全ではないと思いますが、' Contains'でも名前はまだ完全に一致していないかもしれません – LONG

2

なぜ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") 
関連する問題