Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So, here's the thing. There's language integrated query (Linq), and then there's yielded enumeration (a.k.a. Iterators).</p> <p>Linq allows you to define an expression tree that is later executed by something that may or may not be C# (for example the expression could be translated into a SQL query). If you're writing linq there is a good chance your query provider (the thing that does the expression translation) does not support exception handling (much less whatever you're doing that throws exceptions).</p> <p>Interators on the other hand (or "linq to objects") just ends up executing in C#, so you can just go wild with your exception handling.</p> <p>For example w/ linq to objects you can do this:</p> <pre><code>var myList = new[] { "1", "2", "BARF", "3" }; var sum = myList.Select(str =&gt; { try { return Int32.Parse(str); } catch { return 0; } }).Aggregate((x, y) =&gt; x + y); </code></pre> <p>If you're indeed doing linq to objects, and you just want to skip elements where your source IEnumerable threw an exception check out Vladimir Gondarev's answer.</p> <p>The important thing to understand however, is that the anonymous function we just passed to that Select call <strong>is not an Expression (an uncompiled expression tree)</strong>, it is a Func (a delegate pointing to compiled c# code), which means that it will run in the .Net process, even if we replaced myList with a linq to entities table (or some other linq provider). The reason for this is that the C# expression syntax does not support blocks, nor does it support try-catch. Unsurprisingly, given that, the SQL-style Linq statements (from xxx select yyy) also do not support try-catch blocks.</p> <p>However, just because the C# expression syntax doesn't support it doesn't mean you can't do it. But, to be clear, <strong>I do not recommend doing this</strong> because I highly doubt there is a QueryProvider in existence that supports it (aside from the linq to objects provider). For the curious here's how you would create a lambda expression that contains a try-catch block.</p> <pre><code>var parseMethod = typeof(Int32).GetMethod("Parse", new[] { typeof(String) }); var param = Expression.Parameter(typeof(String)); var selectExp = Expression.Lambda&lt;Func&lt;String, Int32&gt;&gt;( Expression.TryCatch( Expression.Call(parseMethod, param), Expression.Catch(typeof(Exception), Expression.Constant(0)) ), param ); var sum = myList.Select(selectExp).Aggregate((x, y) =&gt; x + y); </code></pre> <p>So when somebody implements a QueryProvider backed by a store that supports exception handling, you could use this.</p>
 

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