使用linq搜索字符串以获取列表值 [英] Search string for a list value using linq

查看:62
本文介绍了使用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. Then Any checks whether there is an x in this array where search.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆