Is there an easy way to find one list in another, taking the order into consideration too? (Besides looping through them.) Basically like the way String's .IndexOf
works.
string[] lookInThis = { "a", "b", "c", "d" };
string[] lookForThis1 = { "b", "c" };
string[] lookForThis2 = { "b", "d" };
int FoundLoc = string.Join(",", lookInThis).IndexOf(string.Join(",", lookForThis1));
This works for my strings, but feels like it can be improved.
In my example, these are my expected outputs:
lookForThis1 1
lookForThis2 -1 or something like that.
This should do what you're asking. Not exactly pretty as I just threw it together and I'm no LINQ genie:
public int SublistIndex(string[] lookInThis, string[]lookForThis)
{
int i;
for (i = 0; i < lookInThis.Count(); i++)
{
if (lookInThis.ElementAt(i).Equals(lookForThis.First()))
{
//Found the first element of the list we are searching for
int j;
//Now we need to check if the other elements are there in correct order
for (j = 0; j < lookForThis.Count(); j++)
{
if (i + j == lookInThis.Count())
{
//Reached the end of the lookInThis list with no match
return -1;
}
if (!lookInThis.ElementAt(i + j).Equals(lookForThis.ElementAt(j)))
{
//Sequence is not identical, stop inner loop
break;
}
}
if (j == lookForThis.Count())
{
//found it!
return i;
}
}
}
//reached the end and didn't find it
return -1;
}
Tested with this:
string[] t1 = { "a", "b", "c" };
string[] t2 = { "b", "c" };
string[] t3 = { "b", "d" };
int tt1 = SublistIndex(t1, t2);
int tt2 = SublistIndex(t1, t3);
tt1 = 1
and tt2=-1
You can substitute string
for any type basically, provided you also change the .equals()
comparison to an appropriate one.
How it works:
It loops through lookInThis
and when finding the starting element of lookForThis
it starts another loop to compare them. If it finds any elements don't match it breaks this loop an resumes. If it reaches the end of lookForThis
it returns the index of the first loop. It returns -1 when it reaches the end of lookInThis
. Quick and dirty, so probably not advised for huge lists.
Collected from the Internet
Please contact debug[email protected] to delete if infringement.
Comments