Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if an IEnumerable<T> starts with another IEnumerable<T> in .NET?

I recently came across a scenario where I needed to check if an IEnumerable<T> began with some IEnumerable<T> prefix. I searched and didn't find an existing StackOverflow answer for this, so I decided to contribute my own solution in the form of an answer below.

like image 745
James Ko Avatar asked Jan 29 '23 16:01

James Ko


1 Answers

Your extension is fine but you can use the already existing Enumerable.Zip + All:

var longerSeq = new[] { "SOME", "IMPORTANT", "WORDS" };
var shorterSeq = new[] { "some", "important" };

bool startsWithCaseInsensitive = longerSeq 
    .Zip(shorterSeq, (l, s) =>  string.Equals(l, s, StringComparison.OrdinalIgnoreCase))
    .All(b => b);   // are all bools true? Returns false on first false

Documentation:

The method merges each element of the first sequence with an element that has the same index in the second sequence. If the sequences do not have the same number of elements, the method merges sequences until it reaches the end of one of them

Since Zip is using deferred execution it will not evaluate all if the first already yielded false.

like image 188
Tim Schmelter Avatar answered Feb 01 '23 18:02

Tim Schmelter