search List for string .StartsWith()

后端 未结 10 1746
终归单人心
终归单人心 2021-01-19 00:13

I have a

List

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

10条回答
  •  孤独总比滥情好
    2021-01-19 00:28

    I assume that the really fastest way would be to generate a dictionary with all possible prefixes from your 1500 strings, effectively precomputing the results for all possible searches that will return non-empty. Your search would then be simply a dictionary lookup completing in O(1) time. This is a case of trading memory (and initialization time) for speed.

    private IDictionary prefixedStrings;
    
    public void Construct(IEnumerable strings)
    {
        this.prefixedStrings =
            (
                from s in strings
                from i in Enumerable.Range(1, s.Length)
                let p = s.Substring(0, i)
                group s by p
            ).ToDictionary(
                g => g.Key,
                g => g.ToArray());
    }
    
    public string[] Search(string prefix)
    {
        string[] result;
        if (this.prefixedStrings.TryGetValue(prefix, out result))
            return result;
    
        return new string[0];
    }
    

提交回复
热议问题