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 onIEnumerable<T>, not on the non-genericIEnumerableinterface.It’s not that you can’t enumerate the matches that way; it’s just that the type of
entrywill be inferred asobjectsince theMatchCollectionclass does not implement the genericIEnumerable<T>interface, only theIEnumerableinterface.If you want to stick with implicit typing, you will have to produce an
IEnumerable<T>to help the compiler out:or, the nicer way with explicit-typing (the compiler inserts a cast for you):
The easiest way to produce a smart-enumerable is with the provided extension-method:
This will require a
using MiscUtil.Collections.Extensions;directive in your source file.