score:3

Accepted answer

I guess this would require minimal bound checking - just basic sanity checks. See if this works

IEnumerable<double> GetWindow(List<double> lst, int index, int windowSize) {
    if(index >= lst.Length){
        // Throw proper exception
    }
    return lst.Skip(index-windowSize).Take(Math.Min(index,windowSize));
}

score:0

If you only want to get one window, your accepted answer looks appropriate. But for iterating more than one window, I would go with something like this:

public static IEnumerable<IEnumerable<TSource>> Window<TSource>(
    this IEnumerable<TSource> source, int size)
{
    var q = new Queue<TSource>(size);

    foreach (var value in source)
    {
        if (q.Count >= size)
            q.Dequeue();
        q.Enqueue(value);
        yield return q;
    }
}

Related Articles