Alex Rivera | Logout

Using LINQ to create an IEnumerable<> of delta values

Asked 2010-10-06T15:13:09.213
13

I've got a list of timestamps (in ticks), and from this list I'd like to create another one that represents the delta time between entries.

Let's just say, for example, that my master timetable looks like this:

  1. 10
  2. 20
  3. 30
  4. 50
  5. 60
  6. 70

What I want back is this:

  1. 10
  2. 10
  3. 20
  4. 10
  5. 10

What I'm trying to accomplish here is detect that #3 in the output table is an outlier by calculating the standard deviation. I've not taken statistics before, but I think if I look for the prevalent value in the output list and throw out anything outside of 1 sigma that this will work adequately for me.

I'd love to be able to create the output list with a single LINQ query, but I haven't figured it out yet. Currently I'm just brute forcing it with a loop.

Edit
Report

2 Answers

3

You can use Ani's answer:-

var deltas = list.Zip(list.Skip(1), (current, next) => next - current);

With a super-simple implementation of the Zip extension method:-

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
  this IEnumerable<TFirst> first,
  IEnumerable<TSecond> second,
  Func<TFirst, TSecond, TResult> func)
{
  var ie1 = first.GetEnumerator();
  var ie2 = second.GetEnumerator();

  while (ie1.MoveNext() && ie2.MoveNext())
    yield return func(ie1.Current, ie2.Current);
}

That'll work with 3.5.

answered 2010-10-06T15:38:05.617
-2

LINQ is not really designed for what you're trying to do here, because it usually evaluates value by value, much like an extremely efficient combination of for-loops. You'd have to know your current index, something you don't, without some kind of workaround.

answered 2010-10-06T15:17:07.600

Your Answer