Skip to content

Instantly share code, notes, and snippets.

@hoganlong
Created August 22, 2014 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoganlong/f78176996b4704fa3573 to your computer and use it in GitHub Desktop.
Save hoganlong/f78176996b4704fa3573 to your computer and use it in GitHub Desktop.
public static IEnumerable<T1> FindSubsequence<T1, T2>(
this IList<T1> first,
IList<T2> second,
Func<T1, T2, bool> matchPredicate)
{
T2 firstofsecond = second.FirstOrDefault();
var locations =
first.Select((ele,index) => new { ele = ele, index = index})
.Where(item => matchPredicate(item.ele,firstofsecond))
.Select(item => item.index);
foreach (int i in locations)
{
var subsequence = first.Skip(i).Take(second.Count);
if (subsequence.Zip(second, matchPredicate).All(x => x))
return subsequence;
}
return Enumerable.Empty<T1>();
}
@hoganlong
Copy link
Author

Optimized to not have to perform
var subsequence = first.Skip(i).Take(second.Count);
for the number of elements in first list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment