Search an array in an array
Searching an array in an array is common. It would be nice to have a function like String.IndexOf(string) for arrays. This can be easily achieved by the following extension method of array:
public static class Extensions { /// <summary> /// Reports the index of the first occurrence of the specified array in this instance of array. /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="aSelf">array itself</param> /// <param name="aTarget">search target array</param> /// <returns></returns> public static int IndexOf<T>(this T[] aSelf, T[] aTarget) { int iReturn = -1; if (aSelf.Length >= aTarget.Length) { for (int i = 0; i <= aSelf.Length - aTarget.Length; i++) { bool bMatch = true; for (int j = 0; j < aTarget.Length; j++) { if (!aSelf[i + j].Equals(aTarget[j])) { //end the loop as soon as there is a mismatch bMatch = false; break; } } if (bMatch) { //end the search as soon as there is a match iReturn = i; break; } } } return iReturn; } }