So, do you want the word inside the array to happen first in the target string? It looks like you might need 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();
These steps are in detail:
- Project words into a sequence of word / index pairs, where the index is the index of that word in the target row
- Omit words that did not appear on the target line by deleting pairs where the index is -1 (
string.IndexOf returns -1 if it is not found) - Sort by index to make the earliest word as first pair
- Choose a word in each pair as we no longer need indexes
- Return the first word or
null if the sequence is empty
source share