SmartEnumerable and Regex.Matches
I wanted to use Jon Skeet's SmartEnumerable to loop over a Regex.Matches
but it does not work.
foreac开发者_C百科h (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.
精彩评论