Why can’t I use Linq on a CaptureCollection?

Doing some Regular Expression work, and I wanted to get a simple enumeration of multiple captures in a match group. I tried this:

var caps = from capture in match.Groups[2].Captures select capture.Value;


but Intellisense told me “Could not find an implementation of the query pattern for source type ‘System.Text.RegularExpressions.CaptureCollection’.  ‘Select’ not found.  Consider explicitly specifying the type of the range variable ‘capture’.”

This is because Captures is a specialised collection, not a generic collection, and it doesn’t therefore support IEnumerable<T>. The solution (which I found here) is:

var caps = from capture in pathmatch.Groups[2].Captures.Cast<Capture>() select capture.Value;

adding the Cast to a Capture allows the rest of the Linq query to work.

I love Linq, but just sometimes, it can be a bit impenetrable.


					
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s