Casey Crookston
Casey Crookston

Reputation: 13965

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

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

Then in a single string, if I have:

I would like to eat a pear today

(Ignore case.) In that case I I would want true because pearis 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.

Upvotes: 0

Views: 84

Answers (4)

Dhejo
Dhejo

Reputation: 71

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

Upvotes: 1

FrostyOnion
FrostyOnion

Reputation: 996

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.

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56469

Try this:

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

or

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

Upvotes: 2

tym32167
tym32167

Reputation: 4891

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

Upvotes: 1

Related Questions