Check if one list contains all items from another list in order

后端 未结 4 1187
眼角桃花
眼角桃花 2020-12-16 06:51

How can I determine if List A contains all of the elements from List B in the same order?

List A can have additional elements that List B does not have, but must co

4条回答
  •  情深已故
    2020-12-16 07:15

    I think my version is more efficient.

    public static class CollectionExtension
    {
        public static bool SequenceContain(this IEnumerable target, IEnumerable that)
        {
            var targetEnumerater = target.GetEnumerator();
            var thatEnumerater = that.GetEnumerator();
            var thatHasValue = thatEnumerater.MoveNext();
            var targetHasValue = targetEnumerater.MoveNext();
            var matchCount = 0;
            try
            {
                while (thatHasValue && targetHasValue)
                {
                    if (!EqualityComparer.Default.Equals(targetEnumerater.Current, thatEnumerater.Current))
                    {
                        if (matchCount > 0)
                        {
                            thatEnumerater.Reset();
                            thatEnumerater.MoveNext();
                            matchCount = 0;
                        }
                        targetHasValue = targetEnumerater.MoveNext();
                        continue;
                    }
                    targetHasValue = targetEnumerater.MoveNext();
                    thatHasValue = thatEnumerater.MoveNext();
                    matchCount++;
                }
                return matchCount == that.Count();
            }
            finally
            {
                thatEnumerater.Dispose();
                targetEnumerater.Dispose();
            }
        }
    }
    

提交回复
热议问题