在MatchCollection上使用Linq扩展方法语法

时间:2011-09-01 17:57:04

标签: c# linq

我有以下代码:

MatchCollection matches = myRegEx.Matches(content);

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

有没有办法使用Linq扩展方法语法执行此操作?像这样......

bool result = matches.Any(x => ... );

6 个答案:

答案 0 :(得分:162)

using System.Linq;

matches.Cast<Match>().Any(x => x.Groups["name"].Value.Length > 128)

您只需将其从IEnumerable转换为IEnumerable<Match>(IEnumerable)即可访问IEnumerable上提供的linq扩展。

答案 1 :(得分:44)

当您指定显式范围变量类型时,编译器会插入对Cast<T>的调用。所以这个:

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

完全等同于:

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

也可以写成:

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

在这种情况下,Cast调用是必需的,因为MatchCollection仅实现ICollectionIEnumerable,而不是IEnumerable<T>。几乎所有LINQ to Objects扩展方法都以IEnumerable<T>为目标,除了CastOfType之外,两者都用于转换“弱”类型的集合(例如MatchCollection)到通用IEnumerable<T> - 然后允许进一步的LINQ操作。

答案 2 :(得分:6)

试试这个:

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

供参考,请参阅Enumerable.Cast

  

IEnumerable的元素转换为指定的类型。

基本上,这是将IEnumerable转变为IEnumerable<T>的一种方式。

答案 3 :(得分:2)

我认为会是这样的:

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

答案 4 :(得分:2)

您可以尝试这样的事情:

List<Match> matchList = matches.Cast<Match>().Where(m => m.Groups["name"].Value.Length > 128).ToList();

答案 5 :(得分:-2)

编辑:

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

然后你应该可以调用这个扩展方法把它变成IEnumerable:

 matches.AsEnumerable<Match>().Any(x => x.Groups["name"].Value.Length > 128);