如何在 C# 中进行不区分大小写的列表搜索?

How to make a case insensitive list search in C#?

我一直在尝试创建一个列表搜索方法,在该方法中我可以在不受影响的情况下显示列表中的项目,并且在经历了一周后我可以找到的所有搜索方法后,我意识到我被卡住了。

列表(帖子)存储数组,如果有任何更改,这是我到目前为止使用的搜索功能,效果最好,但它区分大小写,

    string searchKey; 
    Console.WriteLine("\nEnter key: ");
    searchKey = Console.ReadLine(); 

    foreach (string result in posts.Where(logg => logg.Contains(searchKey))) 
    {
        Console.WriteLine("\n{0}", result);
    }

我希望有人知道一些我错过的好方法,即使我开始认为我被搞砸了,应该改用其他系统。

您可以使用 IndexOf 进行不区分大小写的比较:

var query = posts.Where(
    logg => logg.IndexOf(searchKey, StringComparison.CurrentCultureIgnoreCase) != -1);
foreach (string result in query) 
{
    Console.WriteLine("\n{0}", result);
}

请注意,虽然我希望这适用于 IEnumerable<T>,但我怀疑许多 IQueryable<T> 提供商(例如 EF)可能不支持此操作。

最好进行不区分大小写的搜索,但是如果没有可用的搜索,您可以简单地将所有字符串设置为相同的大小写:

string lowerSearchKey = searchKey.ToLower();
foreach (string result in posts.Where(logg => logg.ToLower().Contains(lowerSearchKey))) 
{
    Console.WriteLine("\n{0}", result);
}

显然,这会影响性能,因为您为每次搜索重复调用 ToLower,因此您可能需要考虑存储正在搜索的文本的所有小写版本:

string lowerSearchKey = searchKey.ToLower();
foreach (string result in posts.Where(lowerLogg => lowerLogg.Contains(lowerSearchKey))) 
{
    Console.WriteLine("\n{0}", result);
}

这有点蛮力,可能对某些文化(例如土耳其语)有影响,在这些文化中,大写和小写之间的转换与拉丁字母表中的转换不同,但如果您别无选择,那就是通常你必须做的事情。