Standard: Cannot use linq in MatchCollection regex with .NET Standard 2.0

Created on 15 Feb 2019  路  3Comments  路  Source: dotnet/standard

Hi everyone,

I have the following problem with a .NET Standard 2.0 class library

'MatchCollection' does not contain a definition for 'Select' and no accessible extension method 'Select' accepting a first argument of type 'MatchCollection' could be found (are you missing a using directive or an assembly reference?)

Code

IEnumerable<string> words = Regex.Matches(text, @"([\w]+\.)+[\w]+(?=[\s]|$)").Select(p => p.Value);

I had to move this code from a project that is develope with .NET Core 2.1.

How do I solve this problem? I read https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.matchcollection?view=netstandard-2.0 but I cannot find what the problem is

Thanks in advance

Most helpful comment

 Regex wordMatcher = new Regex(@"\p{L}+");
return wordMatcher.Matches(text).Cast<Match>().Select(c => c.Value);

Hope this helps.

All 3 comments

Historically the Regex collections have not implemented the generic collection interfaces, and the LINQ extension methods you're using operate on the generic interfaces. MatchCollection was updated in .NET Core to implement IList<Match>, and thus can be used with theSelectextension method, but when you move to .NET Standard 2.0, that interface implementation isn't there, and thus you can't just callSelect. Instead, you'll need to use the LINQCastorOfTypeextensions first to go from anIEnumerableto anIEnumerable, and then you can useSelect` on that. Hope that helps.

 Regex wordMatcher = new Regex(@"\p{L}+");
return wordMatcher.Matches(text).Cast<Match>().Select(c => c.Value);

Hope this helps.

For those who still have this problem:

If your code looks like this:

var matches = reg.Matches(connectionString));

change it to this:

var matches = reg.Matches(connectionString).Cast<Match>().Select(x => x);

The difference is in the first code you get back a MatchCollectionobject. In the second you get an IEnumerableof Matchobjects

Was this page helpful?
0 / 5 - 0 ratings

Related issues

KevinWG picture KevinWG  路  3Comments

chrisaut picture chrisaut  路  3Comments

juscelior picture juscelior  路  3Comments

KexyBiscuit picture KexyBiscuit  路  3Comments

ghost picture ghost  路  4Comments