简体   繁体   中英

Find a string in a list of strings in c#

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";

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

return s1.Contains(s2);

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));

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.

Contains' alternative could be IndexOf:

var res = s1.Any(s => s.IndexOf(s2, StringComparison.Ordinal) >= 0)

StringComparison.Ordinal passed as parameter because Contains() also use it internally.

Peter Duniho's answer is generally the best way. I am providing an alternate solution. This one does not require LINQ, lamdas, or loops. This only requires string built-in type's methods.

string.Concat(listOfString).Contains("data");

Note: This approach can lead to incorrect results. For example:

string.Concat("da", "ta").Contains("data");

will return true when it should be false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM