You can nest two loops to do this: for each valid position in the main list, check that each item in the list being searched hits. If it reaches the end without finding, then it returns a negative value, indicating that it did not find it.
The LINQ version, equivalent is at the end of the answer.
public static int FindSubList<T>(IList<T> mainList, IList<T> subList)
{
for (int it = 0; it <= mainList.Count - subList.Count; it++)
{
bool allEquals = true;
for (int it2 = 0; it2 < subList.Count; it2++)
{
if (!mainList[it + it2].Equals(subList[it2]))
{
allEquals = false;
break;
}
}
if (allEquals)
return it;
}
return -1;
}
Using LINQ would look like this, which is the equivalent of the above code:
public static int FindSubList<T>(IList<T> mainList, IList<T> subList)
{
for (int it = 0; it <= mainList.Count - subList.Count; it++)
if (!subList.Where((t, it2) => !mainList[it + it2].Equals(t)).Any())
return it;
return -1;
}
Another alternative using LINQ over IEnumerable
, however this solution is slower than the one above:
public static int FindSubEnumerable<T>(IEnumerable<T> mainList, IEnumerable<T> subList)
{
return
Enumerable.Range(1, mainList.Count())
.FirstOrDefault(it => mainList.Skip(it - 1).Take(subList.Count()).SequenceEqual(subList)) - 1;
}