简体   繁体   中英

comparison goes faulty c# Dictionary<String, string[]>

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.

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, ie where the long string part contains any of the keywords from your list:

categories.Any(x => x.Value.Any(s => part.Contains(s)))

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

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