Using LINQ extension method syntax on a MatchCollection

前端 未结 6 1252
逝去的感伤
逝去的感伤 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 02:03

    When you specify an explicit range variable type, the compiler inserts a call to Cast. 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()
                         .Where(m => m.Groups["name"].Value.Length > 128)
                         .Any();
    

    which can also be written as:

    bool result = matches.Cast()
                         .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. Almost all the LINQ to Objects extension methods are targeted at IEnumerable, 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 - which then allows for further LINQ operations.

提交回复
热议问题