c# - 在 C# 中,搜索列表中的元素但执行 "StartsWith()"搜索的最快方法是什么?

标签 c# .net linq trie startswith

我有一个字符串列表:

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

现在我想要一个这样的函数:

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

但不是包含,我希望它从检查开始,这样 5 个项目中的 4 个将被返回(BIRD 不会)。

最快的方法是什么?

最佳答案

您可以使用 StartsWith Any 内部

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;

关于c# - 在 C# 中,搜索列表中的元素但执行 "StartsWith()"搜索的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19849923/

相关文章:

.net - MSMQ:传送到远程队列时未返回确认

c# - 如何从 F# 调用 Enumerable.Join?

c# - 在\BuildAgent\work\randomnumbers 下找不到文件来创建与\BuildArtifacts\_Build\BranchName.nupkg 匹配的包

c# - 移动字符串框架 k 个字符位置时的 String.Substring 行为

c# - 使用 Result 时出现死锁

c# - 复杂的 C# Linq 算法

c# - LINQ to Entities 无法识别方法 'System.String ToString(Int32)'

c# - 来自另一个类库的基本 Controller 在 Web api 中不起作用

c# - 字符串参数中的类型安全

c# - 对于泛型类型,IsConstructedGenericType 是否始终是 IsGenericTypeDefinition 的否定?