1

I have a list of strings:

 var list = new List<string>();
 list.Add("CAT");
 list.Add("DOG");

var listofItems = new List<string>();
 listofItems .Add("CATS ARE GOOD");
 listofItems .Add("DOGS ARE NICE");
 listofItems .Add("BIRD");
 listofItems .Add("CATAPULT");
 listofItems .Add("DOGGY");

and now i want a function like this:

 listofItems.Where(r=> list.Contains(r));

but instead of Contains, i want it to do a starts with check so 4 out of the 5 items would be returned (BIRD would NOT).

What is the fastest way to do that?

4

4 回答 4

3

您可以在Any中使用StartsWith

listofItems.Where(item=>list.Any(startsWithWord=>item.StartsWith(startsWithWord)))

您可以将其可视化为一个双for循环,第二个循环在遇到案例for时立即中断true

var filteredList = new List<String>();
foreach(var item in listOfItems)
{
    foreach(var startsWithWord in list)
    {
        if(item.StartsWith(startsWithWord))
        {
            filteredList.Add(item)
            break;
        }
    }
}
return filteredList;
于 2013-11-08T01:22:48.377 回答
1

最快的方法是使用另一种数据结构,例如 Trie。基本的 C# 实现可以在这里找到:https ://github.com/kpol/trie

于 2013-11-08T01:27:32.420 回答
0

这应该以更简化的格式为您提供所需的内容:

 var result = listofItems.Select(n =>
 {
      bool res = list.Any(v => n.StartsWith(v));
      return res 
               ? n 
               : string.Empty;
 }).Where(b => !b.Equals(string.Empty));
于 2013-11-08T14:57:44.217 回答
0

The Trie data structure is what you need. Take a look at this more mature library: TrieNet

using Gma.DataStructures.StringSearch;

...

var trie = new SuffixTrie<int>(3);

trie.Add("hello", 1);
trie.Add("world", 2);
trie.Add("hell", 3);

var result = trie.Retrieve("hel");
于 2017-08-31T08:49:45.900 回答