0

I need to check if a list contains all the items and in the same sequence using LINQ and if match found return the last matching element.

var allWords = new List<string> { "A", "B", "C", "D", "E", "F"};
var words = new List<string>() { "D", "E" };

Should return element "E" (because there is a match)

Ashik
  • 21
  • 3

3 Answers3

3

You could do it with Linq.

var allWords = new List<string> { "A", "B", "C", "D", "E", "F","D", "E", "E"};
var words = new List<string>() {"D","E"  };
var indexOfLastOccuranceOfSequence = Enumerable.Range(0, allWords.Count - words.Count + 1)
        .Select(a => allWords.Skip(a).Take(words.Count)).ToList()
        .FindLastIndex(a => a.SequenceEqual(words));
var indexOfLastElement = indexOfLastOccuranceOfSequence+ words.Count() - 1;
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
2

You can find the first word in the list an iterate over them:

int index = allWords.Select((item, i) => new { Item = item, Index = i })
            .First(x => x.Item == words[0]).Index;

foreach(var word in words)
{
     if(allWords[index] != word)
          return(null);
     index += 1;
}
return(index + words.Length - 1);

The above program returns the index of the last match in the allWords. To finding the first occurrence of a word in a list you can see this post.

OmG
  • 18,337
  • 10
  • 57
  • 90
0

You can find the existence by :

List<int> indexes = allWords.Where(x => words.Contains(x)).Select(x => allWords.IndexOf(x)).ToList();
if(indexes.Count() == words.Count())
{
    // then check indexes if SORTED, if so then they are in the same sequence
    return words.Last();  

}
M.Armoun
  • 1,075
  • 3
  • 12
  • 38