Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Like this, with LINQ:</p> <pre><code>int[] array = s.Split(',') .Select(x =&gt; int.Parse(x)) .ToArray(); </code></pre> <p>Note that that will throw an exception if any element of the text isn't an integer. If you want to make it more resilient (if this is user-entered data for example) you'll need to use <code>int.TryParse</code>; at that point life becomes a bit more complicated in terms of the LINQ query.</p> <p>EDIT: To make it parse to an <code>int?[]</code> (with a null value corresponding to each invalid substring) you could do something like:</p> <pre><code>int?[] array = s.Split(',') .Select(x =&gt; { int value; return int.TryParse(x, out value) ? value : (int?)null; }) .ToArray(); </code></pre> <p>As I said, it's not terribly nice :(</p> <p>EDIT: In the comments, Dan commented on the "obsession" with the above approach instead of (presumably) a more imperative approach. In my view even the less-pleasant second version is still easier to read than the imperative alternative. The ugliness is only due to the ugly nature of <code>int.TryParse</code>, which is no less ugly when used in imperative code.</p> <p>If <code>int.TryParse</code> either returned <code>int?</code> or <code>Tuple&lt;bool, int&gt;</code> then it would be as easy as the first version. Even converting from the tuple form to the nullable form would be simple, with one extra projection:</p> <pre><code>int[] array = s.Split(',') .Select(x =&gt; int.TryParseTuple(x)) .Select(tuple =&gt; tuple.First ? tuple.Second : (int?) null) .ToArray(); </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