2012-03-30 16 views
0

這次希望這是一個非常簡單的問題。我在數據庫連接器類中有一個Select方法,如下所示;使用返回列表中的變量<>方法

public List <string> [] Select(string mQuery) 
{ 

    //Create a list to store the result 
    List<string>[] datalist = new List<string>[1]; 
    datalist[0] = new List<string>(); 


    //Open connection 
    if (this.OpenConnection() == true) 
    { 
     //Create Command 
     MySqlCommand cmd = new MySqlCommand(mQuery, mConnection); 
     //Create a data reader and Execute the command 
     MySqlDataReader dataReader = cmd.ExecuteReader(); 

     //Read the data and store them in the list 
     while (dataReader.Read()) 
     { 
      datalist[0].Add(dataReader["id"] + ""); 

     } 

     //close Data Reader 
     dataReader.Close(); 

     //close Connection 
     this.CloseConnection(); 

     //return list to be displayed 
     return datalist; 
    } 
    else 
    { 
     return datalist; 
    } 
} 

當我想訪問「datalist」我假設我這樣稱呼它;

 results = mDB.Select(mQuery); 

但是因爲返回的值是一個列表,我需要將這個變量分配給一個新的列表,像這樣;?

List<string>[] results = new List<string>[1]; 
         results[0] = new List<string>(); 
         results = mDB.Select(mQuery); 
         string result = results[0].ToString(); 

         MessageBox.Show(result); 

此消息框,簡單地產生「System.Collections.Generic.List1(System.String)」

任何有關我在做什麼錯誤邏輯的想法?

+0

你不需要做ToString()。它已經是字符串列表 – 2012-03-30 10:11:13

+0

結果[0]也是集合。結果[0]包含你的數據庫列。您必須選擇 – 2012-03-30 10:12:51

+0

Sorted列之一。乾杯傢伙:D – 2012-03-30 11:30:57

回答

2

請不要將您的列表包裝在數組中?

List<string> results = new List<string>(); 
results = mDB.Select(mQuery); 
string result = results[0].ToString(); 

MessageBox.Show(result); 

無論哪種方式,問題是你試圖顯示一個列表,默認情況下它只是返回它的類型。您應該顯示列表的成員,而不是列表本身。

0

如果您要做的是在例如顯示列表中的內容。以逗號分隔的方式,你可以做這樣的事情:

MessageBox.Show(string.Join(",", list)); 

你得到「System.Collections.Generic.List1(System.String)」是ToStringList只返回一個字符串的原因其類型的表示。

另外,正如其他人指出的,你應該失去陣列。你所要做的就是:

public List<string> Select(string mQuery) 
{ 
    //... 
} 

List<string> list = mDB.Select(mQuery); 
MessageBox.Show(string.Join(",", list)); 
相關問題