List contains list check

I have an IEnumerable<Object> a with 6 elements in chronological order. I want to check if there is an IEnumerable<Object> b list with 3 elements in chronological order.

IEnumerable<Object> a element values: a, b, c, d, f, g

IEnumerable<Object> b element values: b, d, f

Is it possible to execute LINQ?

+4
source share
3 answers

One liner approach of Rolling and Tim is very nice, but he has one little information: b repeated twice.
If this is a problem for you, you can use an iterator based approach. This can be created as an extension method:

 public static bool IsContainedWithinInOrder<T>(this IEnumerable<T> values, IEnumerable<T> reference) { using(var iterator = reference.GetEnumerator()) { foreach(var item in values) { do { if(!iterator.MoveNext()) return false; } while(!Equals(iterator.Current, item)); } return true; } } 

This will only repeat both sequences once and will generally be easier. You would call it like this:

 b.IsContainedWithinInOrder(a); 

Please forgive the method name ...

+7
source

You can use the following:

 bool AContainsEverythingInBInTheSameOrder = a.Intersect(b).SequenceEquals(b); 

a.Intersect(b) returns everything that is in a and b , in the same order in which it appears in a .

+8
source

I assume that you have two lists and you want to check if the second list item has the same order as the same elements in the first list.

May be:

 var allSameOrder = list1.Intersect(list2).SequenceEqual(list2); 

Demo

+6
source

All Articles