Reputation: 11116
I have a IEnumerable<Object> a
with 6 items in chronological order in it.
I want to test if list IEnumerable<Object> b
with 3 items in chronological order.
IEnumerable<Object> a
item values: a,b,c,d,f,g
IEnumerable<Object> b
item values: b,d,f
Is it possible to be done with LINQ ?
Upvotes: 4
Views: 157
Reputation: 174309
The one liner approach of Rawling and Tim is very nice, but it has one little gotcha: b
is iterated twice.
If that is a problem for you, you could 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 would iterate both sequences only once and overall is more lightweight. You would call it like this:
b.IsContainedWithinInOrder(a);
Please forgive the name of the method...
Upvotes: 7
Reputation: 460108
I assume that you have two lists and you want to check if the second list item have the same order as the same items in the first list.
Perhaps:
var allSameOrder = list1.Intersect(list2).SequenceEqual(list2);
Upvotes: 6
Reputation: 50114
You can use the following:
bool AContainsEverythingInBInTheSameOrder =
a.Intersect(b).SequenceEquals(b);
a.Intersect(b)
returns everything that is in both a
and b
, in the same order in which it appears in a
.
Upvotes: 8