gpt4 book ai didi

c# - 改变方法,使他们的搜索变得不区分大小写

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:15 24 4
gpt4 key购买 nike

我有两个方法需要修复,以便当用户搜索“Javascript”时,如果这些方法拼写为“Javascript”或“JavaScript”,则这些方法将返回值 - 大小写无关紧要。从 csv 文件(方法执行搜索的地方)导入数据已经用 LoadData() 完成。可以找到我正在使用的三个文件(JobData.cs、Program.cs、job_data.csv)的完整代码 here .

我需要修复的第一个方法是这个 ( found in JobData.cs, line 143) :

 public static List<Dictionary<string, string>> FindByValue(string searchTerm)
{
LoadData();
//set up a list of jobs that we're going to use to return from this method
List<Dictionary<string, string>> jobs = new List<Dictionary<string, string>>();
//row is a Dictionary<string, string>
foreach (Dictionary<string, string> row in AllJobs)
{
//item is a KeyValuePair
foreach (KeyValuePair<string, string> field in row)
{
string aValue = field.Value;
if (aValue.Contains(searchTerm))
{
jobs.Add(row);
break;
}
}
}
return jobs;
}

也许实现此目的的一种方法是分解 searchTermvalue,以便在用户搜索时它们自动变为小写。这样,即使用户输入JAVAScript,它也会自动转成javascript,并且匹配字符串field中的字符,也变成小写。当然我们还是会返回字段中的原始字符串,无论是“Javascript”还是“JavaScript”。

另一种方法是自动将 searchTerm 设置为不区分大小写,这样无论大小写如何,它都会与 field.Value 匹配。

这样做看起来像这样吗?

  public static List<Dictionary<string, string>> FindByValue(string searchTerm)
{
LoadData();
//set up a list of jobs that we're going to use to return from this method
List<Dictionary<string, string>> jobs = new List<Dictionary<string, string>>();
//row is a Dictionary<string, string>
foreach (Dictionary<string, string> row in AllJobs)
{
//item is a KeyValuePair
foreach (KeyValuePair<string, string> field in row)
{
string aValue = field.Value;
//create new, case-insensitive searchTerm

culture.CompareInfo.IndexOf(searchTerm, aValue, CompareOptions.IgnoreCase) >= 0

if (aValue.Contains(searchTerm))
{
jobs.Add(row);
break;
}
}
}
return jobs;
}

我正在尝试使用 this example不区分大小写的字符串比较。但是使用该行会给我错误消息:

The name "culture" does not exist in the current context
The name "CompareOptions" does not exist in the current context

field.aValue 相比,关于如何使 searchTerms 不区分大小写的任何其他想法?

最佳答案

您使用 IndexOf 而不是 Contains 的想法是正确的,您只需要使用正确的重载 ( the one that takes a StringComparison option )。不区分大小写的比较有多个选项。我使用的是 OrdinalIgnoreCase,但您可以使用最适合您的那个。

取而代之的是:

aValue.Contains(searchTerm)

这样写:

aValue.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) >= 0

关于c# - 改变方法,使他们的搜索变得不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42682392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com