Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to calculate changes of nullable numbers with Linq
    primarykey
    data
    text
    <p>I need to calculate changes off of time series of nullable numbers. The following code gets the job done:</p> <pre><code>public static double?[] GetChanges(double?[] x) { if(x.Length == 1) throw new Exception("Time Series Too Short"); var ret = new double?[x.Length - 1]; for (int i = 1; i &lt; x.Length; i++) { ret[i-1] = (x[i - 1].HasValue &amp;&amp; x[i].HasValue) ? x[i] - x[i - 1] : null; } return ret; } </code></pre> <p>Is there a better way to accomplish that with Linq? The library is using .Net 3.5. Right now I cannot use Zip, because that comes with .Net 4.</p> <p>Edit: following the advice by mquander and Eric Lippert, I have come up with the following code which runs on 3.5:</p> <pre><code>public class Tuple&lt;T&gt; { public Tuple(T first) { First = first; } public T First { get; set; } } public class Tuple&lt;T, T2&gt; : Tuple&lt;T&gt; { public Tuple(T first, T2 second) : base(first) { Second = second; } public T2 Second { get; set; } public static Tuple&lt;T1, T2&gt; New&lt;T1, T2&gt;(T1 t1, T2 t2) { return new Tuple&lt;T1, T2&gt;(t1, t2); } } public static class EnumerableExtensions { public static IEnumerable&lt;Tuple&lt;T, T&gt;&gt; Pairs&lt;T&gt;(this IEnumerable&lt;T&gt; seq) { using (var enumerator = seq.GetEnumerator()) { enumerator.MoveNext(); var prior = enumerator.Current; while (enumerator.MoveNext()) { yield return Tuple&lt;T, T&gt;.New(prior, enumerator.Current); prior = enumerator.Current; } } } } </code></pre> <p>I am using this code as follows:</p> <pre><code> public static IEnumerable&lt;double?&gt; GetChanges2(double?[] x) { if (x.Length == 1) throw new Exception("Time Series Too Short"); return x.Pairs().Select(p =&gt; p.Second - p.First); } </code></pre> <p>Any suggestions on further improvement are welcome. I will be back when I have VS2010 and .Net 4, so that I can try out the approaches suggested in both answers.</p> <p>Thanks!</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.
 

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