If you're searching for a substring you don't need to split the order
string into individual words. You can use the String.Contains
method (in this case, replace words.Contains
with order.Contains
).
if (fruits.Any(w => order.Contains(w)))
{
//do things here
}
if (vegetables.Any(w => order.Contains(w)))
{
//do things here
}
If your search can be case-insenitive, you can use the IndexOf
method.
if(fruits.Any(w => order.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0))
{
//do things here
}
if (vegetables.Any(w => order.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0))
{
//do things here
}
As per comment, this will match substrings of words (e.g. apple
will match apples
). If it has to be whole words only then you can use the regex
in Govind Kumar's answer (which looks to have been copied from this answer). You'd use it like this:
var fruitWords = fruits.Select(w => @"\b" + Regex.Escape(w) + @"\b");
var fPattern = new Regex("(" + string.Join(")|(", fruitWords) + ")");
var fruitMatch = fPattern.IsMatch(order);
var vegWords = fruits.Select(w => @"\b" + Regex.Escape(w) + @"\b");
var vPattern = new Regex("(" + string.Join(")|(", vegWords) + ")");
var vegMatch = vPattern.IsMatch(order);
if(fruitMatch)
{
//fruit matched
}
if(vegMatch)
{
//veg matched
}