Reputation: 455
So my code looks like this
string order = "Im sending you big apples x100";
string[] fruits = { "apples", "big apples", "oranges" };
string[] vegetables = { "tomatoes", "carrots", "cucumber" };
string[] words = order.Split();
if (fruits.Any(w => words.Contains(w)))
{
//do things here
}
if (vegetables.Any(w => words.Contains(w)))
{
//do things here
}
I want to be able to find depending on the order string what exactly is it if its possible, now in my case when the string array has 2 words in sequence this code doesnt work, how can i do it when my string array has 2 words. I want to find only if it has "big apples" i know i could do it only "apples" but i want to find sequence words in the order string.
Upvotes: 1
Views: 5907
Reputation: 8461
This will let you loop through each type of fruit and then check the value. Since you already have an approach which uses Lambda syntax, I thought I'd share a non lambda version!
foreach (var fruit in fruits)
{
if (order.contains(fruit))
{
//do things here
}
}
foreach (var veg in vegetables)
{
if (order.contains(veg))
{
//do things here
}
}
Upvotes: -1
Reputation: 69372
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
}
Upvotes: 8
Reputation: 11
var escapedWords = words.Select(w => @"\b" + Regex.Escape(w) + @"\b");
var pattern = new Regex("(" + string.Join(")|(", escapedWords) + ")");
var q = pattern.IsMatch(myText);
Upvotes: 0