HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Use linq to compute length of line defined as array of points

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqlinecomputearraylengthpointsusedefined

Problem

I have an array of points:

Point[] line; // { Point(1,1), Point(2,3), Point(1,1) }


Assuming Point has the relevant operators, what's the most linq-y way of computing the length of this line?

My best effort so far is:

float length = Enumerable.Range(0, line.Length-2)
    .Select(pointIndex => (line[pointIndex+1] - line[pointIndex]).Magnitude)
    .Sum();


Seems like there's a lot of subscripting in there though.

I would think there's a way to do something like this pseudocode:

float length = line.PairwiseMap(p1, p2 => (p2 - p1).Magnitude).Sum();


?

Solution

Another possible answer (first time I've ever suggested two answers) is to keep your existing approach, but modified just a little bit by using .Select()'s under-appreciated little brother that gives you access to an index variable:

float length = line.Skip(1)
    .Select((point, index) => (point - line[index]).Magnitude)
    .Sum();


Heck, speaking of overloads. You can also keep your existing approach but use .Sum()'s overload:

Enumerable.Range(0, line.Length - 1)
    .Sum(pointIndex => (line[pointIndex + 1] - line[pointIndex]).Magnitude)

Code Snippets

float length = line.Skip(1)
    .Select((point, index) => (point - line[index]).Magnitude)
    .Sum();
Enumerable.Range(0, line.Length - 1)
    .Sum(pointIndex => (line[pointIndex + 1] - line[pointIndex]).Magnitude)

Context

StackExchange Code Review Q#13567, answer score: 4

Revisions (0)

No revisions yet.