通常最简单的方法是使用Cast
扩展方法:
IEnumerable<Match> strongMatches = matches.Cast<Match>()
请注意,这是延迟的并且以流的方式提供其数据,因此您没有完整的“集合” - 但它是用于LINQ查询的非常好的数据源。
如果在查询表达式中为范围变量指定类型,则会自动调用
Cast
:
因此,要完全转换您的查询:
public static int MaxSequence(string str)
{
return (from Match match in Regex.Matches(str, "H+|T+")
select match.Value.Length into matchLength
orderby matchLength descending
select matchLength).First();
}
或者
public static int MaxSequence(string str)
{
MatchCollection matches = Regex.Matches(str, "H+|T+");
return matches.Cast<Match>()
.Select(match => match.Value.Length)
.OrderByDescending(len => len)
.First();
}
事实上,你在这里不需要调用OrderByDescending
然后再调用First
- 你只是想要最大值,而Max
方法可以帮助你得到它。更好的是,它允许你从源元素类型投影到你要查找的值,因此你可以省去Select
:
public static int MaxSequence(string str)
{
MatchCollection matches = Regex.Matches(str, "H+|T+");
return matches.Cast<Match>()
.Max(match => match.Value.Length);
}
如果你有一个集合,其中包含
一些正确类型的元素,但也可能有一些不是,那么你可以使用
OfType
。 当
Cast
遇到“错误”类型的项目时会抛出异常;
OfType
只是跳过它们。