user3185171
user3185171

Reputation:

Creating multidimension list

I have seperate list of values reflecting X,Y,Z coordinates properties.

List<double> PointX;
List<double> PointY;
List<double> PointZ;

Is it possible to create a '3D List' such that i would have

Point = (PointX,PointY,PointZ)

Upvotes: 2

Views: 620

Answers (5)

Nic
Nic

Reputation: 1310

The answers based on Zip sound pretty good. However, you could also create an extension method for List.

something like:

  public static List<double> Xs(this List<Point3D> pts) {
        List<double> xs = new List<double>(pts.Count);

        foreach (Point3D pt in pts) {
            xs.Add(pt.X);
        }
        return xs;
    }

    public static List<double> Ys(this List<Point3D> pts) {
        List<double> ys = new List<double>(pts.Count);

        foreach (Point3D pt in pts) {
            ys.Add(pt.Y);
        }
        return ys;
    }

    public static List<double> Zs(this List<Point3D> pts) {
        List<double> zs = new List<double>(pts.Count);

        foreach (Point3D pt in pts) {
            zs.Add(pt.Z);
        }
        return zs;
    }

Upvotes: 0

TVOHM
TVOHM

Reputation: 2742

var points = PointX.Zip(PointY, (x, y) => new { X = x, Y = y })
    .Zip(PointZ, (xy, z) => new { X = xy.X, Y = xy.Y, Z = z });
var point = points.First();
double px = point.X;
double py = point.Y;
double pz = point.Z;

You can use Zip to join the 3 collections into an anonymous type. In this example I zip x,y into an anonymous type, then I zip that type with the z collection to return a collection of anonymous a type that represents x,y and z.

Upvotes: 0

mark_h
mark_h

Reputation: 5487

You could use a list of tuples e.g.

        var list = new List<Tuple<double, double, double>>(){new Tuple<double, double, double>(3, 4, 5)};

I also like rboe's solution but I would consider making the Point3D class immutable;

public class Point3D
{
    public double X { get; private set; }
    public double Y { get; private set; }
    public double Z { get; private set; }

    public Point3D(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }
}

Upvotes: 1

Ralf B&#246;nning
Ralf B&#246;nning

Reputation: 15465

What's about

public class Point3D {
    public double X {get; set;}
    public double Y {get; set;}
    public double Z {get; set;}
}

List<Point3D> list = new List<Point3D>();
for (int i = 0; i < PointX.Count; i++) {
    list.Add(new Point3D { X = PointX[i], Y = PointY[i], Z = PointZ[i] });
}

Upvotes: 1

D Stanley
D Stanley

Reputation: 152634

You can use nested Zip calls to take values from each list:

var points = 
    PointX.Zip(PointY.Zip(PointZ, (y,z) => new {y, z})
            , (x, yz) => new Point(x, yz.y, yz.z));

Upvotes: 3

Related Questions