How to find index of sublist in list?

This is essentially the same problem as substring searching (indeed, a list where order is significant is a generalisation of “string”).

Luckily computer science has considered this problem frequently for a long time, so you get to stand on the shoulders of giants.

Take a look at the literature. Some reasonable starting points are:

http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm

http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm

http://en.wikipedia.org/wiki/Rabin-karp

Even just the pseudocode in the wikipedia articles is enough to port to C# quite easily. Look at the descriptions of performance in different cases and decide which cases are most likely to be encountered by your code. (I’m thinking the first from what you say about the search-key list being short).

Leave a Comment