[英]Checking if string exists in List C#
我一直在編寫一個程序,將學生數據(姓名和年齡)存儲在.txt文件中。 我現在正在執行刪除方法。 但是,當用戶輸入一個字符串時,我希望它將輸入內容與我的List<string>
的字符串進行比較,該List<string>
充滿了名稱。 碼:
string tempFileName;
string inputSel; // Selection string for delete
Console.WriteLine(" -- Deleting Grade {0} -- ", grade);
Console.WriteLine("- Enter a student name to delete: ");
foreach (string file in fileNames)
{
tempFileName = file.Replace(".txt", "");
studentNames.Add(tempFileName);
}
foreach (string name in studentNames)
{
Console.Write("{0}\n", name);
}
Console.WriteLine();
Console.Write("> ");
inputSel = Console.ReadLine();
string input = inputSel.ToLower();
string tempString;
bool foundString = false;
foreach (string file in studentNames)
{
tempString = file.ToLower();
if (inputSel == tempString)
{
foundString = true;
}
}
if (!foundString)
{
Console.WriteLine("Wrong name entered!");
Console.WriteLine("Returning to grades menu..");
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
return;
}
如您所見,該程序將inputSel
存儲到input
(ToLower())中,然后比較studentNames List<string>
每個字符串,如果找到匹配項,則會翻轉foundString bool
,但是即使我輸入一個匹配(例如,它說JacobMusterson,我輸入JacobMusterson,它應該跳過“找不到學生”,但是沒有。
您應該使用輸入而不是inputSel
if (input == tempString)
{
foundString = true;
}
由於行:
string input = inputSel.ToLower();
您在哪里輸入inputSel的較低版本
我建議您在字符串中使用IngonreCase.Compare不制作ToLower()
var b = string.Compare("a","A",StringComparison.OrdinalIgnoreCase);
它將返回0,如果等於看這里
編輯:
我個人將使用:
var exists = studentNames.Any(x=>string.Compare(x,inputSel,StringComparison.OrdinalIgnoreCase)==0);
您可以這樣簡單地做到這一點:
Boolean foundString = studentNames.Exists(name => name.ToLower().Equals(input));
如果使用List
Contains
方法,它將更具可讀性和有效性:
foreach (string file in studentNames)
{
tempString = file.ToLower();
if (inputSel == tempString)
{
foundString = true;
}
}
if (!foundString)
{
Console.WriteLine("Wrong name entered!");
Console.WriteLine("Returning to grades menu..");
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
return;
}
可以重寫:
if(!studentNames.Contains(inputSel, StringComparer.Create(CultureInfo.InvariantCulture, true)))
{
Console.WriteLine("Wrong name entered!");
Console.WriteLine("Returning to grades menu..");
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
return;
}
只需對您的foreach循環發表一點評論。 如果您已經發現字符串在集合中,那么您也總是在循環中遍歷所有條目。
您可以通過替換最后的foreach來提高代碼的性能。
嘗試:
bool foundString = studentNames.Select(file => file.ToLower()).Any(tempString => inputSel == tempString);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.