You can nest two loops to do this: for each valid position of the main list, check whether each item of the list being searched beats. If you reach the end without finding, then returns a negative value, indicating that you did not find.
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 the 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 on IEnumerable
, however this solution is slower than 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;
}
Thanks, but I’m looking for a simpler version without using for. Using for I’ve already managed to do.
– Renato Dinhani
I have indicated a LINQ solution! It is at the end of the answer.
– Miguel Angelo
Now I have indicated another alternative, using pure LINQ, about
IEnumerable
instead of lists.– Miguel Angelo
The version with
IEnumerable
is slower, I recommend the second solution, which is using LINQ onIList
.– Miguel Angelo
@Miguelangelo in your code should not be <byte> instead of <int> ?
– user6026
@FCCDIAS: Really! I made the codes generic so that any kind of data is supported.
– Miguel Angelo
The LINQ version with Ilist is still in trouble, I’ll fix it.
– Miguel Angelo
I tested the last option, and it worked correctly. Thank you.
– Renato Dinhani
Fixed, when converting to generic, inverti unintentionally the test condition.
– Miguel Angelo