Robert Smith Robert Smith - 1 year ago 155
C# Question

Convert array of doubles to list object using linq

I have the following array of coordinates:

double[] points = { 1, 2, 3, 4, 5, 6 };

Then I have the following class:

public class clsPoint
public double X { get; set; }
public double Y { get; set; }

I need to copy the points into List objects. Where the first point in the array is the X and the second point in the array is the Y. Here is what I have so far but it is not correct:

List<clsPoint> lstPoints = points
.Select(coord => new clsPoint
X = coord[0],
Y = coord[1]

Expected Results

clsPoint Objects List (lstPoints)
X = 1 , Y = 2
X = 3 , Y = 4
X = 5 , Y = 6

Any help would be appreciated. Thanks.

Answer Source

You can generate a sequence of consecutive values until the half your array, then you can project using those values as index to get the pairs.

var result=Enumerable.Range(0, points.Length / 2).Select(i=>new clsPoint{X=points[2*i],Y=points[2*i+1]});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download