我無法找到有效但簡單的方法來檢查列表是否包含另一個列表(保留順序)。它類似於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