I needed a function that would return the index of one SubList within another List. Think of this as is List1 a sub list of List2.
{4, 5, 6} is a sublist of {1, 2, 3, 4, 5, 6, 7, 8, 9}{4, 6, 5} is not a sublist of {1, 2, 3, 4, 5, 6, 7, 8, 9}
Note that these are lists and not sets. In the world of sets, the order is not important and both of the above tests would be true.
This class became the core of an application that searches for certain phrases within a larger body of text. Completing a text based search was pretty straight forward but I also wanted to implement a phonetic based search. It was easy to translate the original body of text into a List<string> of individual words and a second List<string> of their phonetic representation (using SoundEx or Metaphone). The number of elements in both lists was the same. This allowed me to do a search on the phonetic words and then translate them back to their original text by using the corresponding element in the original list. More on the word scanning project some other time.
The word project used Lists<string> but the class allows for any type. The example uses integers.
ListSearch<int> listSearch = new ListSearch<int>();
List<int> list = new List<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
List<int> subList = new List<int>(new int[] { 4, 5, 6 });
Console.WriteLine("Should return 4 : {0}", listSearch.IndexOf(list, subList));
subList = new List<int>(new int[] { 4, 6, 5 });
Console.WriteLine("Should return -1 : {0}", listSearch.IndexOf(list, subList));
Console.ReadKey();
Here is the code. I had an initial version that used some recursion and worked fine. This version, based on a suggestion by Luke Zhang of Microsoft, is a bit cleaner. Thanks Luke!
public static class ListSearch<T>
{
public static int IndexOf(List<T> list, List<T> sublist)
return IndexOf(0, list, sublist);
}
public static int IndexOf(int start, List<T> list, List<T> sublist)
for (int i = start; i <= list.Count - sublist.Count; i++)
int j = 0;
while (j < sublist.Count)
if (!list[i + j].Equals(sublist[j])) break;
if (j < sublist.Count) j++;
if (j == sublist.Count) return i;
return -1;
Remember Me
a@href@title, strike
Powered by: newtelligence dasBlog 2.0.7226.0
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008, Andrew Robinson
E-mail