1

I have a table in SQL Server that stores x, y, z values as floats, I would like to get the values and store them in a tridimensional array.

I have been searching and I have seen people would go for adding values to a list, as we do not know how many items we could get, like:

List<int> list = new List<int>();

using (SqlDataReader reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
         list.Add(reader.GetInt32(0));
    }    
}
return list.ToArray();

However I do not know if it is possible to read table and get and store elements at once

I was trying to get three lists like this:

List<double> xValuesList = (from IDataRecord r in dataReader
                     select (double)r["xVal"]
                    ).ToList();

List<double> yValuesList = (from IDataRecord r in dataReader
                     select (double)r["yVal"]
                    ).ToList();
List<double> zValuesList = (from IDataRecord r in dataReader
                     select (double)r["zVal"]
                    ).ToList();

and then loop and get a tridimensional array from all these 3 lists..

But I think using a struct or something would be better, but I do not know how to do it.

1
  • 1
    Are you sure that you need a tridimensional array and not a tuple with three elements? Commented Apr 12, 2014 at 23:32

1 Answer 1

2

If I understood your question correctly, try to create a class like this:

public class Point3D
{
    public readonly double X;
    public readonly double Y;
    public readonly double Z;

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

And read a data from the table directly into the list of instances of this class as follows:

List<Point3D> list = new List<Point3D>();

using (SqlDataReader reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        list.Add(new Point3D(reader.GetDouble(0), reader.GetDouble(1), reader.GetDouble(2)));
    }    
}
Sign up to request clarification or add additional context in comments.

3 Comments

If I already have a struct called Point but has other attributes How can I change the code to work? public struct Point : IEquatable<Point>, IComparable<Point> { public double _X; public double _Y; public double _Z; // getters setters and constructors...
so if the select statement is string lcQuery = "SELECT X, Y,Z FROM cmYTAB WHERE inId = '" + id + "'"; I would get values by reader.GetDouble(0), reader.GetDouble(1), reader.GetDouble(2) right?
Yup, right! And also you should pass these values to the constructor of the Point class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.