Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search List<string> for string .StartsWith()

I have a

List<string>

with 1500 strings. I am now using the following code to pull out only string that start with the string prefixText.

foreach(string a in <MYLIST>)
{            
    if(a.StartsWith(prefixText, true, null))
    {
        newlist.Add(a);                   
    }            
}

This is pretty fast, but I'm looking for google fast. Now my question is if I arrange the List in alphabetical order, then compare char by char can I make this faster? Or any other suggestions on making this faster?

like image 640
Scott Selby Avatar asked May 06 '12 18:05

Scott Selby


People also ask

How do you check if a string startsWith another string?

The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.

Can we use startsWith in list in Python?

Python example code use str. startswith() to find it a string starts with some string in a list. In the example list of substrings has converted into a tuple using tuple(list) in order to return a boolean if str contains substrings found it.

How do I find a string in a list?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

Is startsWith () a valid string method in Python?

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .


2 Answers

Thus 1500 is not really a huge number binary search on sorted list would be enough probably. Nevertheless most efficient algorithms for prefix search are based on the data structure named Trie or Prefix Tree. See: http://en.wikipedia.org/wiki/Trie

Following picture demonstrates the idea very briefly: enter image description here

For c# implementation see for instance .NET DATA STRUCTURES FOR PREFIX STRING SEARCH AND SUBSTRING (INFIX) SEARCH TO IMPLEMENT AUTO-COMPLETION AND INTELLI-SENSE

like image 61
George Mamaladze Avatar answered Oct 07 '22 06:10

George Mamaladze


You can use PLINQ (Parallel LINQ) to make the execution faster:

var newList = list.AsParallel().Where(x => x.StartsWith(prefixText)).ToList()
like image 45
Adi Lester Avatar answered Oct 07 '22 04:10

Adi Lester