Using LINQ extension method syntax on a MatchCollection

前端 未结 6 1249
逝去的感伤
逝去的感伤 2020-12-13 01:20

I have the following code:

MatchCollection matches = myRegEx.Matches(content);

bool result = (from Match m in matches
               where m.Groups["nam         


        
相关标签:
6条回答
  • 2020-12-13 01:46

    You can try something like this:

    List<Match> matchList = matches.Cast<Match>().Where(m => m.Groups["name"].Value.Length > 128).ToList();
    
    0 讨论(0)
  • 2020-12-13 01:49

    EDIT:

     public static IEnumerable<T> AsEnumerable<T>(this IEnumerable enumerable)
     {
          foreach(object item in enumerable)
              yield return (T)item;
     }
    

    Then you should be able to call this extension method to turn it into an IEnumerable:

     matches.AsEnumerable<Match>().Any(x => x.Groups["name"].Value.Length > 128);
    
    0 讨论(0)
  • 2020-12-13 02:03

    When you specify an explicit range variable type, the compiler inserts a call to Cast<T>. So this:

    bool result = (from Match m in matches
                   where m.Groups["name"].Value.Length > 128
                   select m).Any();
    

    is exactly equivalent to:

    bool result = matches.Cast<Match>()
                         .Where(m => m.Groups["name"].Value.Length > 128)
                         .Any();
    

    which can also be written as:

    bool result = matches.Cast<Match>()
                         .Any(m => m.Groups["name"].Value.Length > 128);
    

    In this case the Cast call is required because MatchCollection only implements ICollection and IEnumerable, not IEnumerable<T>. Almost all the LINQ to Objects extension methods are targeted at IEnumerable<T>, with the notable exceptions of Cast and OfType, both of which are used to convert a "weakly" typed collection (such as MatchCollection) into a generic IEnumerable<T> - which then allows for further LINQ operations.

    0 讨论(0)
  • 2020-12-13 02:05

    Try this:

    var matches = myRegEx.Matches(content).Cast<Match>();
    

    For reference, please see Enumerable.Cast:

    Converts the elements of an IEnumerable to the specified type.

    Basically it's one way of turning an IEnumerable into an IEnumerable<T>.

    0 讨论(0)
  • 2020-12-13 02:06
    using System.Linq;
    
    matches.Cast<Match>().Any(x => x.Groups["name"].Value.Length > 128)
    

    You just need to convert it from an IEnumerable to an IEnumerable<Match> (IEnumerable<T>) to get access to the LINQ extension provided on IEnumerable<T>.

    0 讨论(0)
  • 2020-12-13 02:08

    I think it would be something like this:

    bool result = matches.Cast<Match>().Any(m => m.Groups["name"].Value.Length > 128);
    
    0 讨论(0)
提交回复
热议问题