2013-09-30 215 views
0

我想在C#中獲得一個相當大的SQL查詢到一個數組中。但是,查詢中的值由雙精度和字符串組成。我如何解釋?因爲使用下面的方法(只是將所有內容都放入字符串中)在我的工作表中不起作用,因爲數字格式爲文本。C#二維數組和字符串

String sql = "SELECT Ticker, Cusip, Shares, value, Price, " +.... 

string[,] data = new string[5000, 10]; //multi-dimentional array 

string connectionString = Database.ConnectionString(); 
using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
    connection.Open(); 
    using (SqlCommand command = new SqlCommand(sql, connection)) 
    { 

     SqlDataReader reader = command.ExecuteReader(); 
     while (reader.Read()) 
     { 
      String ticker = (string)reader["ActTicker"]; 
      String cusip = (string)reader["Cusip9"]; 
      double shares = (double)reader["shares"]; 
      double price = (double)reader["price"]; 
      double value = (double)reader["value"]; 

      data[row, 0] = ticker; 
      data[row, 1] = "=iferror(bdp(\"" + cusip + " cusip\", \"GICS_SECTOR_NAME\"),0)"; 
      data[row, 2] = "=iferror(bdp(\"" + cusip + " cusip\", \"SECURITY_TYP\"),0)"; 
      data[row, 3] = "=iferror(bdp(\"" + cusip + " cusip\", \"CUR_MKT_CAP\"),0)"; 
      data[row, 4] = "=iferror(bdp(\"" + cusip + " cusip\", \"VOLUME_AVG_10D\"),0)"; 
      data[row, 5] = shares.ToString(); 
      data[row, 6] = value.ToString(); 
      data[row, 7] = price.ToString(); 
      data[row, 8] = "=iferror(bdp(\"" + cusip + " cusip\", \"last price\"),0)"; 
     } 
    } 
} 
+0

爲什麼你不能使用'詞典<雙,字符串>'這個? – Brian

+1

是否有任何理由使用數組。這是DataTables的用途。它們可以從SQL Query自動加載。 – Vulcronos

+0

你應該學習如何使用類和列表。如果超過5000個條目,則會出現問題。 –

回答

0

您可以使用一個DataTable,或者如果你想一些更輕巧,強類型,然後創建自己的自定義數據結構。

public struct MyCustomData 
{ 
    String ticker; 
    String cusip; 
    double shares; 
    double price; 
    double value; 
} 

的製造陣列出來的

MyCustomData[] data = new MyCustomData[5000]; 
. 
. 
. 
data[row].ticker = ticker; 
data[row].cusip = "=iferror(bdp(\"" + cusip + " cusip\", \"GICS_SECTOR_NAME\"),0)"; 
. 
. 
. 
0
public SqlConnection myConnection = new SqlConnection(""); 

    public DataTable Select(string sTSQL) 
    { 
     DataTable dt = new DataTable(); 
     try 
     { 
      myConnection.Open(); 
      SqlDataReader myReader = null; 
      SqlCommand myCommand = new SqlCommand(sTSQL, myConnection); 
      myReader = myCommand.ExecuteReader(); 

      dt.Load(myReader); 

     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
      dt = null; 
     } 
     finally 
     { 
      try 
      { 
       myConnection.Close(); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e.ToString()); 
      } 
     } 

     return dt; 
    }