如何在 C# 中作为字典进行搜索

How to search as a dictionary in C#

我正在尝试在我的术语集中查找搜索词。

术语集合数组:

[0] "windows"
[1] "dual sim"
[2] "32 gb"
[3] "Intel i5"

现在我搜索以下术语

search term= "32 gb"                 return -> 2 (position of array)
search term ="android 32 gb"         return -> 2 (position of array)
search term ="android mobile 32 gb"  return -> 2 (position of array)
search term= "32 GB"                 return -> 2 (position of array)
search term= "32gb"                  return -> not match 
search term= "dual sim 32"           return -> 1 (position of array)

那么如何在 C# .net 中做到这一点 任何搜索库或搜索词典都可以提供此功能

请advise/suggestion同样

谢谢!

int index =  Array.IndexOf(YourCollection,  YourCollection.Where(x=>x.Contains("32 gb")).FirstOrDefault());

一个简单的逻辑给你:在每次迭代中遍历你的集合(数组)检查搜索键的值,如果两者都等于 return 它的索引,否则 return -1(表示未找到项目)

public static int GetMatchingIndex(string searchKey)
 {
     string[] MyValues = new string[] { "windows", "dual sim", "32 gb", "Intel i5" };
     for (int i = 0; i < MyValues.Count(); i++)
     {
          if (searchKey.IndexOf(MyValues[i], StringComparison.InvariantCultureIgnoreCase) >= 0)
             return i;
     }
     return -1;
 }

您可以像下面这样调用此方法(Example Here):

string searchTerm = "32 gb";
int itemIndex= GetMatchingIndex(searchTerm); // This will give 2

您可以使用 Array.FindIndex 并执行此操作。

var array = new string [] {"windows","dual sim","32 gb","Intel i5"};

string searchString = "android 32 gb";
var index = Array.FindIndex(array, x=> searchString.IndexOf(x) >=0);

如果您正在寻找不区分大小写的搜索,请使用此选项。

var index = Array.FindIndex(array, x=> searchString.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >=0);

勾选这个Demo

public int SearchArray(string searchTerm) {
    return arrayList.IndexOf(
    arrayList.Cast<string>()
    .FirstOrDefault(i => searchTerm.Contains(i)));
}