简体   繁体   中英

SmartEnumerable and Regex.Matches

I wanted to use Jon Skeet's SmartEnumerable to loop over a Regex.Matches but it does not work.

foreach (var entry in Regex.Matches("one :two", @"(?<!\w):(\w+)").AsSmartEnumerable())

Can somebody please explain me why? And suggest a solution to make it work. Thanks.

The error is:

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

EDIT: I think you forgot to insert the .AsSmartEnumerable() call in your sample code. The reason that won't compile is because the extension-method only works on IEnumerable<T> , not on the non-generic IEnumerable interface.


It's not that you can't enumerate the matches that way; it's just that the type of entry will be inferred as object since the MatchCollection class does not implement the generic IEnumerable<T> interface, only the IEnumerable interface.

If you want to stick with implicit typing, you will have to produce an IEnumerable<T> to help the compiler out:

foreach (var entry in Regex.Matches("one :two", @"(?<!\w):(\w+)").Cast<Match>())
{ 
   ...
} 

or, the nicer way with explicit-typing (the compiler inserts a cast for you):

foreach (Match entry in Regex.Matches("one :two", @"(?<!\w):(\w+)"))
{ 
   ...
} 

The easiest way to produce a smart-enumerable is with the provided extension-method:

var smartEnumerable = Regex.Matches("one :two", @"(?<!\w):(\w+)")
                           .Cast<Match>()
                           .AsSmartEnumerable();

foreach(var smartEntry in smartEnumerable)
{
   ...
}

This will require a using MiscUtil.Collections.Extensions; directive in your source file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM