I need to calculate the changes in the time series of zero numbers. The following code does the job:
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 < x.Length; i++) { ret[i-1] = (x[i - 1].HasValue && x[i].HasValue) ? x[i] - x[i - 1] : null; } return ret; }
Is there a better way to achieve this with Linq? The library uses .Net 3.5. I canβt use Zip right now because it is happening with .Net 4.
Edit: following the advice of mquander and Eric Lippert, I came up with the following code that works on 3.5:
public class Tuple<T> { public Tuple(T first) { First = first; } public T First { get; set; } } public class Tuple<T, T2> : Tuple<T> { public Tuple(T first, T2 second) : base(first) { Second = second; } public T2 Second { get; set; } public static Tuple<T1, T2> New<T1, T2>(T1 t1, T2 t2) { return new Tuple<T1, T2>(t1, t2); } } public static class EnumerableExtensions { public static IEnumerable<Tuple<T, T>> Pairs<T>(this IEnumerable<T> seq) { using (var enumerator = seq.GetEnumerator()) { enumerator.MoveNext(); var prior = enumerator.Current; while (enumerator.MoveNext()) { yield return Tuple<T, T>.New(prior, enumerator.Current); prior = enumerator.Current; } } } }
I use this code as follows:
public static IEnumerable<double?> GetChanges2(double?[] x) { if (x.Length == 1) throw new Exception("Time Series Too Short"); return x.Pairs().Select(p => p.Second - p.First); }
Any suggestions for further improvement are welcome. I will be back when I have VS2010 and .Net 4 so that I can try the approaches suggested in both answers.
Thanks!
source share