2014-10-03 69 views
2

我建立了一個系統,可以從數據庫表中加載單詞,但我需要將這些單詞添加到「選擇」類型(語法構建所需的類型)的列表中。C#從數據庫中加載單詞並將它們添加到「選擇」類型的列表中?

這是從數據庫中檢索我的請求的話代碼:

  List<string> newWords = new List<string>(); 
      newWords = LexicalOperations.WordLibrary().ToList(); 

      Choices dbList = new Choices(); //Adding them to a Choice List 
      if (newWords.Count != 0) 
      { 
       foreach (string word in newWords) 
       { 
        dbList.Add(word.ToString()); 
       } 
      } 
      else dbList.Add("Default"); 

這是我從表中檢索數據的代碼:

public class LexicalOperations 
{ 
     public static List<string> WordLibrary() 
     { 
       List<string> WordLibrary = new List<string>(); 

       string conString = "Data Source=.;Initial Catalog=QABase;Integrated Security=True"; 

       using (SqlConnection connection = new SqlConnection(conString)) 
       { 
        connection.Open(); 
        string sqlIns = "select WordList from NewWords"; 
        SqlCommand cmd = new SqlCommand(sqlIns, connection); 

        SqlDataAdapter sda = new SqlDataAdapter(cmd); 
        DataSet ds = new DataSet(); 
        sda.Fill(ds); 

        foreach (DataRow dr in ds.Tables[0].Rows) 
        { 
         WordLibrary.Add(dr[0].ToString()); 
        } 

       } 

       return WordLibrary; 
      } 
     } 

然而,這將引發異常: System.FormatException其中還指出消息:

Fo rmatException是未處理的

雙引號字符串無效。

,當我建立一個語音語法生成器的選擇列表此錯誤是拋出:

GrammarBuilder graBui = new GrammarBuilder(dbList); 
Grammar Gra = new Grammar(graBui); 

我在做什麼錯?爲了從數據庫中正確檢索單詞並將它們添加到選項列表中應該做些什麼?

+0

哪一行會引發錯誤? – DGibbs 2014-10-03 15:15:33

+2

*「雙引號字符串無效」*聽起來像是由dbList.Add()所做的任何事情引發的自定義異常? - 錯誤在哪裏,當前字符串是什麼樣的? – 2014-10-03 15:15:58

+0

與問題無關,但前兩行可寫爲'List newWords = LexicalOperations.WordLibrary();' – Steve 2014-10-03 15:17:54

回答

2

問題似乎是你的語法類不能用雙引號處理字符串。
因此,解決問題的最簡單方法是通過輸入刪除雙引號。

public class LexicalOperations 
{ 
    public static List<string> WordLibrary() 
    { 
     List<string> WordLibrary = new List<string>(); 
     string conString = "Data Source=.;Initial Catalog=QABase;Integrated Security=True"; 

     string sqlIns = "select WordList from NewWords"; 
     using (SqlConnection connection = new SqlConnection(conString)) 
     using (SqlCommand cmd = new SqlCommand(sqlIns, connection)) 
     { 
      connection.Open(); 
      using(SqlDataReader reader = cmd.ExecuteReader()) 
      { 
       while(reader.Read()) 
       { 
        string noQuotes = reader.GetString(0).Replace("\"", ""); 
        WordLibrary.Add(noQuotes); 
        // In alternative you could also opt to not add a string with double quotes 
        // string noQuotes = reader.GetString(0); 
        // if(noQuotes.IndexOf("\"") < 0) 
        // WordLibrary.Add(noQuotes); 
       } 
      } 
     } 
     return WordLibrary; 
    } 
} 

注意,我也有除去SqlDataAdapterDataSet的填充。在這種情況下是無用的,並且明顯阻礙了性能,因爲您正在執行兩個循環。第一個由框架執行以填充DataSet,第二個由您的代碼添加單詞到List<string>變量

相關問題