C# 什么';将非泛型集合转换为泛型集合的最佳方法是什么?

C# 什么';将非泛型集合转换为泛型集合的最佳方法是什么?,c#,generics,linq-to-objects,C#,Generics,Linq To Objects,我最近一直在自学LINQ,并将其应用于各种小谜题。然而,我遇到的一个问题是,LINQto对象只适用于泛型集合。是否有将非泛型集合转换为泛型集合的秘密技巧/最佳做法 我当前的实现将非泛型集合复制到一个数组中,然后对其进行操作,但我想知道是否有更好的方法 public static int maxSequence(string str) { MatchCollection matches = Regex.Matches(str, "H+|T+"); Match[] matchArr

我最近一直在自学LINQ,并将其应用于各种小谜题。然而,我遇到的一个问题是,LINQto对象只适用于泛型集合。是否有将非泛型集合转换为泛型集合的秘密技巧/最佳做法

我当前的实现将非泛型集合复制到一个数组中,然后对其进行操作,但我想知道是否有更好的方法

public static int maxSequence(string str)
{
    MatchCollection matches = Regex.Matches(str, "H+|T+");
    Match[] matchArr = new Match[matches.Count];
    matches.CopyTo(matchArr, 0);
    return matchArr
        .Select(match => match.Value.Length)
        .OrderByDescending(len => len)
        .First();
}
匹配.Cast();

最简单的方法通常是扩展方法:

IEnumerable<Match> strongMatches = matches.Cast<Match>();


如果您有一个集合,其中某些元素的类型正确,但某些元素的类型可能不正确,则可以使用<代码>强制转换遇到“错误”类型的项时引发异常<类型的code>只是跳过它。

您可以使用或在
IEnumerable
上进行转换<代码>强制转换将在元素无法强制转换为指定类型时抛出非法强制转换,而类型的
将跳过任何无法转换的元素。

非常感谢!我不确定我是如何在文档中遗漏了该方法的,但这正是我要寻找的!还感谢您提供有关使用Max()的提示
IEnumerable<Match> strongMatches = matches.Cast<Match>();
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();
}
public static int MaxSequence(string str)
{      
    MatchCollection matches = Regex.Matches(str, "H+|T+");
    return matches.Cast<Match>()
                  .Max(match => match.Value.Length);
}