使用linq搜索字符串以获取列表值 [英] Search string for a list value using linq
问题描述
大家好,我的Linq学习仍在继续,说我有一个包含
{ < span class =code-string> Pete, Lynne};
和包含
的字符串
< span class =code-string>这是一个字符串,可能包含也可能不包含我们正在寻找的单词,如Pete
我该怎么办?在字符串中搜索列表中的任何单词?
我尝试过的方法:
谷歌搜索,但只找到搜索列表而不是字符串
的示例string input = 这是一个字符串,可能包含也可能不包含我们正在寻找的单词,如Pete 跨度>;
List< string> search = new 列表< string>(){ Pete , Lynne};
bool found = input.Split(' ')。任意(x = > search.Contains(x));
它的工作方式如下:字符串被拆分为一个单词数组。然后任何
检查此数组中是否有x
,其中search.Contains(x)
。
Enumerable.Any(TSource)方法(IEnumerable(TSource))(System.Linq) [ ^ ]
我认为你的意思是相反的,就像这样:
string input = 这是一个字符串,可能包含也可能不包含我们正在寻找的单词,如Pete;
List< string> search = new 列表< string>(){ Pete , Lynne};
bool found = search.Any(s = > input.Contains(s)) ;
最后一行相当于:
bool found = search.Where(s = > input.Contains(s))。Any();
Hi all, my Linq learning continues, say I have a List containing
{"Pete","Lynne"};
and a string containing
"This is a string and may or may not contain a word we are looking for like Pete"
How can I search the string for any word in my list ?
What I have tried:
Googling but only found examples that search lists not the string
string input = "This is a string and may or may not contain a word we are looking for like Pete"; List<string> search = new List<string>() { "Pete", "Lynne"}; bool found = input.Split(' ').Any(x => search.Contains(x));
It works like this: the string gets split into an array of words. ThenAny
checks whether there is anx
in this array wheresearch.Contains(x)
.
Enumerable.Any(TSource) Method (IEnumerable(TSource)) (System.Linq)[^]
I think you meant it the other way around, like this:
string input = "This is a string and may or may not contain a word we are looking for like Pete"; List<string> search = new List<string>() { "Pete", "Lynne" }; bool found = search.Any(s => input.Contains(s));
The last line is equivalent to:
bool found = search.Where(s => input.Contains(s)).Any();
这篇关于使用linq搜索字符串以获取列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!