简体   繁体   中英

Do any items in List<string> contain part of a separate string

Let's say I have List<string> that looks like this:

  • Apple
  • Pear
  • Peach
  • Plum

Then in a single string, if I have:

I would like to eat a pear today

(Ignore case.) In that case II would want true because pear is found both in the list and in the string. But if I had a string:

I would like to eat a strawberry today

Then I would get false because none of the List<string>'s are found in the sentence.

I've been playing around with various things like:

string result = Fruits.FirstOrDefault(s => s.IndexOf(sentence) > 0);

Where Fruits is the List<string> and sentence is the other string. Not nailing it.

Try this:

bool result = Fruits.Any(s => sentence.ToLower().Contains(s.ToLower()));

or

bool result = Fruits.Any(s => sentence.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0);

you need to check in this way =>

string result = Fruits.Any(s => sentence.IndexOf(s) > -1);

or

string result = Fruits.Any(s => sentence.Contains(s));

If you are open to another approach it could be done using the following method:

public static bool ListItemInString(List<string> listOfStrings, string stringToCheck) {
    foreach(string str in listOfStrings) {
        if (stringToCheck.ToUpper().Contains(str.ToUpper())) {
            // return true if any of the list items are found in stringToCheck
            return true;
        }
    }
    // if the method has not returned true by this point then we return false
    // to indicate none of the list items were found within the string
    return false;
}

This method loops through your list and checks each item against your designated string. It will return try if at any point in the foreach loop it finds that one of your list items is contained within the string, otherwise it will return false. It also takes in consideration your non-case sensitive request by converting both strings to uppercase before performing its search through the string.

Edit : I understand this is more of a manual approach. The previous answers on this post could similarly be worked into a method to improve code readability if this is an operation being performed multiple times.

As per the initial question, if you are looking for matching strings in the sentence and not boolean result following code should help:

List<string> Fruits = new List<string> { "Apple", "Pear", "Peach", "Plum" };
var sentence = "I would like to eat a pear and apple today";
var sentenceLower = sentence.ToLower(); 
var delimiter = ",";
var match = Fruits
  .Where(s => sentenceLower.Contains(s.ToLower()))
  .Aggregate((i, j) => i + delimiter + j);

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