Using linq to retrieve pairs of Points from collection?
I ha开发者_JS百科ve 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.
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!)
精彩评论