Reputation: 495
Good day all,
I have a Dictionary<String, String[])>
, with a key => value example like the following:
{ "Eten/drinken", new string[] { "canteen", "mcdonald's", "mimi" } }
I need to compare a string part
with one of the values of the Dictionary:
if (categories.Any(x => x.Value.Contains(part))) {
category = categories.FirstOrDefault(x => x.Value.Contains(part)).Key;
}
In one scenario part = "mcdonald's veghel veghel"
, which makes the comparison with the Dictionary value come back false
.
Why is it false? "mcdonald's veghel veghel"
does contain mcdonald's
and zero-space comparisons do go the way they should.
Upvotes: 1
Views: 128
Reputation: 29026
Actually the String.Contains
method will check for any specified subsring present in the given string. unfortunately there is no x.Value
that contains the given string, whereas the given values contains item/s of x.Value, so you have to change your query like the following:
var collectionResult = categories.FirstOrDefault(x => x.Value.Any(s=> part.Contains(s)));
if(collectionResult != null)
{
var selectedKey = collectionResult.Key;
}
Upvotes: 2
Reputation: 726669
Expression inside lambda x.Value.Contains(part)
means that any of the elements of {"canteen", "mcdonald's", "mimi"}
contains the string "mcdonald's veghel veghel"
, which is false
. You wanted the inverse of the condition, i.e. where the long string part
contains any of the keywords from your list:
categories.Any(x => x.Value.Any(s => part.Contains(s)))
Upvotes: 3