How to compare string to String Array in C#?

I have an string;

String uA = "Mozilla/5.0 (iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508 Twitter for iPhone";

String[] a= {"iphone","ipad","ipod"};

It must return ipad because ipad is in the first match ipad at the string. In other case

String uA = "Mozilla/5.0 (iPhone/iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508";

Same string array first match to iPhone.

Jon Skeet
people
quotationmark

So you want the word within the array which occurs earliest in the target string? That sounds like you might want something like:

return array.Select(word => new { word, index = target.IndexOf(word) })
            .Where(pair => pair.index != -1)
            .OrderBy(pair => pair.index)
            .Select(pair => pair.word)
            .FirstOrDefault();

Those steps in detail:

  • Project the words into a sequence of word/index pairs, where the index is the index of that word within the target string
  • Omit words that didn't occur in the target string by removing pairs where the index is -1 (string.IndexOf returns -1 if it's not found)
  • Order by index to make the earliest word occur as the first pair
  • Select the word within each pair, as we no longer care about indexes
  • Return the first word, or null if the sequence is empty

people

See more on this question at Stackoverflow