-6

I'm try to find the search term in my term collection.

array of term collection :

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

Now I search bellow term

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)

So how can do like this in C# .net Can any search library or search dictionary provide this feature

Please advise/suggestion for same

Thanks!

Kalpesh Boghara
  • 418
  • 3
  • 22

4 Answers4

2

You could use Array.FindIndex and do this.

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);

if you are looking for case insensitive search, use this.

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

Check this Demo

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

A simple Logic For you: Iterate through your collection(Array) in each iteration check the value with search key, if both are equals The return its Index, else return -1( which means item not found)

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;
 }

You can call This Method Like the Following(Example Here):

string searchTerm = "32 gb";
int itemIndex= GetMatchingIndex(searchTerm); // This will give 2
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • my search term is "android intel i5" and return is -1 that's wrong output should be 3 – Kalpesh Boghara Jul 13 '16 at 05:08
  • @KalpeshBoghara I had an update in the post, changed the comparison to this: ` if (searchKey.IndexOf(MyValues[i], StringComparison.InvariantCultureIgnoreCase) >= 0)` take a look – sujith karivelil Jul 13 '16 at 05:22
-1
int index =  Array.IndexOf(YourCollection,  YourCollection.Where(x=>x.Contains("32 gb")).FirstOrDefault());
Sami
  • 3,686
  • 4
  • 17
  • 28
-1
public int SearchArray(string searchTerm) {
    return arrayList.IndexOf(
    arrayList.Cast<string>()
    .FirstOrDefault(i => searchTerm.Contains(i)));
}
Marcius Bezerra
  • 137
  • 1
  • 2
  • 11
  • Why use ArrayList instead of List or string[] ? Also this solution has unecessary high complexetiy. – CSharpie Jul 13 '16 at 05:09
  • you should explain better your answer. It is not okay just post code without explanation. OP should understand what answers mean. – StepUp Jul 13 '16 at 06:34