Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The easiest way to write any iterator is with an iterator block, for example:</p> <pre><code>static IEnumerable&lt;T&gt; Where&lt;T&gt;(this IEnumerable&lt;T&gt; data, Func&lt;T, bool&gt; predicate) { foreach(T value in data) { if(predicate(value)) yield return value; } } </code></pre> <p>The key here is the "<code>yield return</code>", which turns the method into an iterator block, with the compiler generating an enumerator (<code>IEnumerator&lt;T&gt;</code>) that does the same. When called, generic type inference handles the <code>T</code> automatically, so you just need:</p> <pre><code>int[] data = {1,2,3,4,5}; var odd = data.Where(i=&gt;i%2 != 0); </code></pre> <p>The above can be used with anonymous types just fine.</p> <p>You can, of coure, specify the <code>T</code> if you want (as long as it isn't anonymous):</p> <pre><code>var odd = data.Where&lt;int&gt;(i=&gt;i%2 != 0); </code></pre> <p>Re <code>IEnumerable</code> (non-generic), well, the simplest approach is for the caller to use <code>.Cast&lt;T&gt;(...)</code> or <code>.OfType&lt;T&gt;(...)</code> to get an <code>IEnumerable&lt;T&gt;</code> first. You can pass in <code>this IEnumerable</code> in the above, but the caller will have to specify <code>T</code> themselves, rather than having the compiler infer it. You can't use this with <code>T</code> being an anonymous type, so the moral here is: don't use the non-generic form of <code>IEnumerable</code> with anonymous types.</p> <p>There are some slightly more complex scenarios where the method signature is such that the compiler can't identify the <code>T</code> (and of course you can't specify it for anonymous types). In those cases, it is usually possible to re-factor into a different signature that the compiler <em>can</em> use with inference (perhaps via a pass-thru method), but you'd need to post actual code to provide an answer here.</p> <hr> <p>(updated)</p> <p>Following discussion, here's a way to leverage <code>Cast&lt;T&gt;</code> with anonymous types. The key is to provide an argument that can be used for the type inference (even if the argument is never used). For example:</p> <pre><code>static void Main() { IEnumerable data = new[] { new { Foo = "abc" }, new { Foo = "def" }, new { Foo = "ghi" } }; var typed = data.Cast(() =&gt; new { Foo = "never used" }); foreach (var item in typed) { Console.WriteLine(item.Foo); } } // note that the template is not used, and we never need to pass one in... public static IEnumerable&lt;T&gt; Cast&lt;T&gt;(this IEnumerable source, Func&lt;T&gt; template) { return Enumerable.Cast&lt;T&gt;(source); } </code></pre>
 

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