Home > front end >  Why does RegularExpressions.GroupCollection enumerable not work with Linq extension methods?
Why does RegularExpressions.GroupCollection enumerable not work with Linq extension methods?

Time:09-30

I was working with regular expressions in C# and when you test a regex you can obtain a list of captured groups, which is an instance of System.Text.RegularExpressions.GroupCollection.

All the stuff about regexes is not relevant. What is relevant is that I cannot query the instance of GroupCollection using LINQ extension methods (like Where, First, etc.), Visual Studio just tells me those method don't exist.

Initially I thought this was not a queryable type, however by peeking at the class declaration in Visual Studio, here's what it looks like:

public class GroupCollection : ICollection<Group>, IEnumerable<Group>, IEnumerable,
    IEnumerable<KeyValuePair<string, Group>>, IList<Group>,
    IReadOnlyCollection<KeyValuePair<string, Group>>, IReadOnlyCollection<Group>,
    IReadOnlyDictionary<string, Group>, IReadOnlyList<Group>, ICollection, IList
{
    ...
}

Now, correct me if I'm wrong, but shouldn't LINQ be available on any IEnumerable<T> ? Am I just wrong in thinking that? What am I missing?

CodePudding user response:

You'll need to access the Values property.

GroupCollection c;

c.Values.Where ...

It is the values property that is an IEnumerable of Group.

P.S. I see this for the declaration of GroupCollection:

public class GroupCollection : 
    IList<Group>, 
    IReadOnlyList<Group>, 
    IList, 
    IReadOnlyDictionary<string, Group>

Although IList should derive from IEnumerable, so, yup, also a little confused as to why we don't see Linq methods on the GroupCollection class.

CodePudding user response:

Apparently, I didn't consider an important detail: the code I'm writing is part of a library that targets multiple versions of .NET:

<TargetFrameworks>net5.0-windows;netcoreapp3.1;net461</TargetFrameworks>

Apparently, in .NET 4.6.x the GroupCollection class does NOT implement IEnumerable, thus why the LINQ expressions are not available.

Visual Studio when peeking at internal framework code apparently shows you the definition of the first framework in the list, so I was seeing the definition for .NET 5

  • Related