tags:

views:

36

answers:

1

I have a collection of Points, stored in a PointCollection.

I need the points in the collection to draw lines.

So, for example, if a point collection has four points, that will be three lines.

Example:

(1) Point(1,1) (2) Point(2,2) (3) Point(3,3) (4) Point(4,4)

If I have a list of points, comprised of the four points referenced above, I am going to draw three lines, using the following logic:

Line 1 - Point(1,1), Point(2,2) Line 2 - Point(2,2), Point(3,3) Line 3 - Point(3,3), Point(4,4)

Is there a way, using Linq, Lambda Expressions, Extension Methods etc., to extract these points in pairs, from my initial list of points? That way I can iteratively take each pair of points and draw my lines?

Thanks.

+2  A: 

I'm off out in a second, but here's a horrible solution (in that it uses side-effects):

Point previous = default(Point);

return points.Select(p => { Point tmp = previous;
                            previous = p;
                            return new { p1 = tmp, p2 = previous };
                          })
             .Skip(1); // Ignore first (invalid) result

You can probably do better with System.Interactive and Scan, but otherwise it would probably be best to write a new extension method. Something like this (using Tuple from C# 4):

public static IEnumerable<Tuple<T, T>> ConsecutivePairs<T>(this IEnumerable<T> sequence)
{
    // Omitted nullity checking; would need an extra method to cope with
    // iterator block deferred execution
    using (IEnumerator<T> iterator = sequence.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            yield break;
        }
        T previous = iterator.Current;
        while (iterator.MoveNext())
        {
            yield return Tuple.Create(previous, iterator.Current);
            previous = iterator.Current;
        }
    }
}

(Apologies for any mistakes - written in a hurry!)

Jon Skeet
I am amused how many comply with a horrible request and give a horrible solution instead of saying - you better do it this way.
Hamish Grubijan
I don't think it's a horrible request though...
Jon Skeet
It is possible, though, that there is context or other conditions not fully represented in the question that makes the solution not horrible. And you can usually count on at least one answer telling you everything that was wrong with your question.
Mikeb
I'm limited to a solution that is based on .NET 3.5.
Chris
@chris: it would be easy enough to create your own tuple type.
Jon Skeet
Jon - thank you so much for your help - it worked perfectly.
Chris