To find a counter, he must find all matches in order to count them. Given that you still stop after three, this seems a little pointless.
Use the MatchCollection lazy score in combination with the LINQ Take method to complete only the first three matches. It is generally recommended to use StringBuilder instead of concatenating strings in a loop:
StringBuilder builder = new StringBuilder(...); foreach (var match in matches.Cast<Match>().Take(3)) { builder.AppendFormat("... {0} ...", matches[i].Value); }
(Maybe changing a StringBuilder here won't make much difference, but it's a good habit to come in. Cast is required because Enumerable.Take only works with the generic IEnumerable<T> .)
source share