Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The simplest way is usually the <a href="http://msdn.microsoft.com/en-us/library/bb341406.aspx" rel="noreferrer"><code>Cast</code></a> extension method:</p> <pre><code>IEnumerable&lt;Match&gt; strongMatches = matches.Cast&lt;Match&gt;(); </code></pre> <p>Note that this is deferred and streams its data, so you don't have a full "collection" as such - but it's a perfectly fine data source for LINQ queries.</p> <p><code>Cast</code> is automatically called if you specify a type for the range variable in a query expression:</p> <p>So to convert your query completely:</p> <pre><code>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(); } </code></pre> <p>or</p> <pre><code>public static int MaxSequence(string str) { MatchCollection matches = Regex.Matches(str, "H+|T+"); return matches.Cast&lt;Match&gt;() .Select(match =&gt; match.Value.Length) .OrderByDescending(len =&gt; len) .First(); } </code></pre> <p>In fact, you don't need to call <code>OrderByDescending</code> and then <code>First</code> here - you just want the maximal value, which the <code>Max</code> method gets you. Even better, it lets you specify a projection from a source element type to the value you're trying to find, so you can do without the <code>Select</code> too:</p> <pre><code>public static int MaxSequence(string str) { MatchCollection matches = Regex.Matches(str, "H+|T+"); return matches.Cast&lt;Match&gt;() .Max(match =&gt; match.Value.Length); } </code></pre> <p>If you have a collection which has <em>some</em> elements of the right type but some which may not be, you can use <a href="http://msdn.microsoft.com/en-us/library/bb360913.aspx" rel="noreferrer"><code>OfType</code></a> instead. <code>Cast</code> throws an exception when it encounters an item of the "wrong" type; <code>OfType</code> just skips over it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload