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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With