c# - 在 lambda 表达式中使用 substring 和 foreach

标签 c# lambda

    Dictionary<int, string> names= GetNames().Where(x =>  
x.Value.StartsWith("test") | x.Value.StartsWith(" " + "test")).ToDictionary(x => x.Key, y => y.Value);

getNames() 方法的值是这样的:

约翰测试

测试特拉维斯

测试Metsaoy

使用上面的代码行,我只得到最后两个条目,但我还想要第一个,因为第二个字符串以“test”开头。

所以,我需要修改上面的where语句。我试过这样的事情:

.Where(x =>  
    foreach ( xx in x.Value.Split(' ') ) { if ( xx.StartsWith("text") ) true; })

我怎样才能做到这一点?

最佳答案

var res = GetNames().Where(kvp => kvp.Value.Split()
                                 .Any(s => s.StartsWith("Test") || s.StartsWith("test")));

您可以选择使用 String.Contains 而不是 StartsWithAny lambda 中。

关于c# - 在 lambda 表达式中使用 substring 和 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34332081/

相关文章:

python - 不带部分的 python lambda 函数列表

c++ - 如何在 C++ 中构建复合 for 循环?

c++ - Lambda 函数不能用不同的签名编译

c# - 在 DispatcherTimer EventHandler 中添加额外的字符串参数

c# - C#中的继承概念

c# - 对 WCF 服务的异步调用不保留 CurrentCulture

java - 使用函数引用时出现奇怪的语法错误

c# - 获取列表所有索引的所有结果

c# - 如何获得粒子系统之一?

C# .Contains() 检查它是否是一个 URL