snippetcsharpModerate
Simplify LINQ to Create Step Values
Viewed 0 times
linqcreatesimplifystepvalues
Problem
Assume the following definition:
If
I want to convert
Here's what I have:
I think my ruby background might have gotten the best of me as that doesn't seem very readable. Any thoughts on how to make things more approachable?
public class DataPoint {
public DateTime Date { get; private set; }
public double Value { get; private set; }
public DataPoint(DateTime date, double value) { Date = date; Value = value; }
}If
var points = ... //a date ordered list of DataPointsI want to convert
points into a list or array that represents the steps between each subsequent value. E.g. [3, 5, 6, 10.5] would go to [3, 2, 1, 4.5] with dates.Here's what I have:
var steps = (new[] {points.First()})
.Concat(points
.Skip(1)
.Zip(points,
(curr, prev) => new DataPoint(curr.Date, curr.Value - prev.Value)))I think my ruby background might have gotten the best of me as that doesn't seem very readable. Any thoughts on how to make things more approachable?
Solution
In my opinion, the
Concat part is what's throwing it off. There is a lesser utilized Select overload that provides access to the index, which could be used like so (ignoring the DataPoint part to make a minimal example):double[] points = new double[] { 3, 5, 6, 10.5 };
points.Select ((p, i) => p - (i == 0 ? 0 : points[i - 1]));Code Snippets
double[] points = new double[] { 3, 5, 6, 10.5 };
points.Select ((p, i) => p - (i == 0 ? 0 : points[i - 1]));Context
StackExchange Code Review Q#54168, answer score: 10
Revisions (0)
No revisions yet.