Dictionary<int, string> names= GetNames().Where(x =>
x.Value.StartsWith("test") | x.Value.StartsWith(" " + "test")).ToDictionary(x => x.Key, y => y.Value);
getNames()方法的值如下:
John Testing
Test Travis
测试Metsaoy
使用上面的代码行我只得到最后两个条目,但我也想要第一个条目,因为第二个字符串以“test”开头。
所以,我需要修改上面的where语句。我试过这样的事情:
.Where(x =>
foreach ( xx in x.Value.Split(' ') ) { if ( xx.StartsWith("text") ) true; })
我怎样才能做到这一点?
答案 0 :(得分:4)
var res = GetNames().Where(kvp => kvp.Value.Split()
.Any(s => s.StartsWith("Test") || s.StartsWith("test")));
可选择代替StartsWith
,您可以在Any
lambda中使用String.Contains
。
答案 1 :(得分:2)
你试过这个吗?
x.Value.StartsWith("test") || x.Value.Contains(" test")
您必须在查询中使用它,如下所示:
var names= GetNames()
.Where(x => x.Value.StartsWith("test") || x.Value.Contains(" test"))
.ToDictionary(x => x.Key, y => y.Value);
希望有所帮助
答案 2 :(得分:2)
尝试:
var parser = new Regex(@"\bTest", RegexOptions.Compiled);
GetNames().Where(x => parser.IsMatch(x.Value)).ToDictionary(x => x.Key, y => y.Value)