Correctly filling up multidimensional array
I'm trying to fill an multidimensional array with data from an SQL database. Because there isn't an function like myarray.Add for this I figured out something else. But it is not working! I'm using C# .net The following line is giving errors: arr[counter2] = {myDataReader["rating"], myDataReader["date"]};
public string[,] getData(int id)
{
string queryString = "SELECT rating, date FROM rating WHERE id = '" + id + "'";
SqlDataReader myDataReader = Database.sqlDataReader(queryString);
if (myDataReader.HasRows)
{
int counter = 0;
while (myDataReader.Read())
{
counter++;
}
string[,] arr = new string[counter, 2];
开发者_如何学JAVA int counter2 = 0;
while (myDataReader.Read())
{
counter2++;
arr[counter2] = {myDataReader["rating"], myDataReader["date"]};
}
}
return arr;
}
Could someone help me fix this or explain me another (and probably better) way of doing the same thing?
That's overly complicated. Try this:
public string[,] getData(int id)
{
string queryString = "SELECT rating, date FROM rating WHERE id = '" + id + "'";
List<string[]> data = new List<string[]>();
using(SqlDataReader myDataReader = Database.sqlDataReader(queryString))
while(myDataReader.Read())
data.Add(new int[] { (string)myDataReader["rating"], (string)myDataReader["date"] });
return data.ToArray();
}
Plus, you really shouldn't concatenate your SQL statement.
Either use a jagged array:
public string[][] getData(int id)
...
string[][] arr = new string[counter][];
...
arr[counter2] = new string[] {myDataReader["rating"], myDataReader["date"]};
Or assign each entry individually:
arr[counter2,0] = myDataReader["rating"];
arr[counter2,1] = myDataReader["date"];
You can use ArrayLists in an ArrayList It is better for database results because they are dynamic (no need to declare size). See the following post: Multi-dimensional arraylist or list in C#?
精彩评论