Efficiently Combine MatchCollections in .NET regular expressions
There are three steps here:
- Convert the
MatchCollection
's toIEnumerable<Match>
's - Concatenate the sequences
- Filter by whether the
Match.Success
property is true
Code:
IEnumerable<Match> combined = matchNoCase.OfType<Match>().Concat(matchCase.OfType<Match>()).Where(m => m.Success);
Doing this creates a new enumerator which only executes each step as the next result is fetched, so you only end up enumerating through each collection once, total. For example, Concat() will only start executing the second enumerator after the first runs out.