我无法找到有效但简单的方法来检查列表是否包含另一个列表(保留顺序)。它类似于string.Contains(字符串)功能。LINQ列表包含另一个列表(连续)
说我有整数四个类别:
A = [1, 2, 3, 4, 5]
B = [2, 3]
C = [5, 6, 7]
D = [3, 2, 4]
A.Contains(B)
将是真实的,而A.Contains(C)
和A.Contains(D)
会是假的。
我宁可不使用迭代器,如果它可以帮助,但我不能想象一个有效的方法来做到这一点;下面的代码是非常低效的。
public static bool IsSequentiallyEqual<T>(this IEnumerable<T> lhs, IEnumerable<T> rhs)
{
return lhs.Zip(rhs, (a, b) => a.Equals(b)).All(isEqual => isEqual == true);
}
public static bool StartsWith<T>(this IEnumerable<T> haystack, IEnumerable<T> needle)
{
return haystack.Take(needle.Count()).IsSequentiallyEqual(needle);
}
public static bool Contains<T>(this IEnumerable<T> haystack, IEnumerable<T> needle)
{
var result = list.SkipWhile((ele, index) => haystack.Skip(index).StartsWith(needle));
return result.Count() >= needle.Count();
}
你有多少物品? (也就是说,效率至关重要,还是只是想要效率不是很低的东西?) – Ryan
它不足以满足效率要求,但它会很好 – hehewaffles
http://stackoverflow.com/questions/3529727/how-to-find-index-of-sublist-in-list – Ryan