C# check if a string contains an element from a collection

List of strings

if(listOfStrings.Any(s => myString.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0))
{
    result = listOfStrings[myString];
}

Dictionary, accessing string as a Key

if(dictionaryOfStrings.Keys.Any(c => myString.IndexOf(c, StringComparison.OrdinalIgnoreCase) > 0))
{
    result = dictionaryOfStrings[myString];
}

Dictionary, accessing string as a Value

if(dictionaryOfStrings.Values.Any(c => myString.IndexOf(c, StringComparison.OrdinalIgnoreCase) > 0))
{
    foreach (KeyValuePair<string, string> pair in dictionaryOfStrings)
    {
        if (myString.Equals(pair.Value))
        {
            result = pair.Key;
        } 
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *