Reputation: 31249
So I have a question regarding how to count the starts with of a string in linq. Let me explain with some test cases
Test case #1
var target="test";
var source="test2";
The output should be 4
Test case #2
var target="te";
var source="test2";
The output should be 2
Test case #3:
var target="tet";
var source="test2";
The output should be 0. Because the source do not starts with target
So I came up with this function:
private int CountStartsWith(string source, string target)
{
if (!source.StartsWith(target))
return 0;
return source.ToCharArray()
.Zip(target.ToCharArray(), (s1, s2) => (s1 == s2))
.TakeWhile(match => match)
.Count();
}
It works for the test cases that I have. But my question is can this be done in an easier way?
Upvotes: 3
Views: 468
Reputation: 186803
You may try
return source.StartsWith(target, StringComparison.OrdinalIgnoreCase) ? target.Length : 0;
Upvotes: 4