在C#的字符串列表中查找字符串 [英] Find a string in a list of strings in c#

查看:1018
本文介绍了在C#的字符串列表中查找字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找字符串列表是否包含C#中的特定字符串. 例如:假设我的列表中有3个条目

I am trying to find if a list of strings contains a specific string in C#. for example: Suppose I have 3 entries in my list

list<string> s1 = new List<string>(){
  "the lazy boy went to the market in a car", 
  "tom", 
  "balloon"};
string s2 = "market";

现在,如果s1包含s2,我想返回true.

Now I want to return true if s1 contains s2, which it does in this case.

return s1.Contains(s2);

这将返回false,这不是我想要的.我正在阅读有关谓词的信息,但是对于这种情况,它可能没有多大意义. 预先感谢.

This returns false which is not what I want. I was reading about Predicate but could not make much sense out of it for this case. Thanks in advance.

推荐答案

最简单的方法是分别搜索每个字符串:

The simplest way is to search each string individually:

bool exists = s1.Any(s => s.Contains(s2));

List<string>.Contains()方法将检查是否有任何整个字符串与您要求的字符串匹配.您需要检查每个单独的列表元素才能完成所需的操作.

The List<string>.Contains() method is going to check if any whole string matches the string you ask for. You need to check each individual list element to accomplish what you want.

请注意,这可能是一项耗时的操作,如果列表中包含大量元素,字符串很长,尤其是在您要搜索的字符串不存在或找不到的情况下仅在列表的末尾.

Note that this may be a time-consuming operation, if your list has a large number of elements in it, very long strings, and especially in the case where the string you're searching for either does not exist or is found only near the end of the list.

这篇关于在C#的字符串列表中查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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