繁体   English   中英

检查列表C#中是否存在字符串

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM