2016-10-21 27 views
0

在一個程序,我一直在努力,有三個步驟來獲取數據到一個已經創建了一個字典:C#填充字典直接從SqlDataReader的

  1. 執行SQL命令
  2. 拉那些結果成DataTable,然後
  3. DataTableDictionary

代碼:

var myDr = myLookup.ExecuteReader(); 
dt.Load(myDr); 
customerLookup = dt.AsEnumerable() 
    .ToDictionary(key => key.Field<string>("code"), 
    value => value.Field<string>("customerText")); 

我的問題是,是否有可能「切掉中間人」,可以這麼說,並將數據從SqlDataReater直接拖到字典?或者是否有必要先將它拉入DataTable?如果我想要做什麼是可能的,有人可以發佈代碼給我試試嗎?

非常感謝!

+0

試試這個:myDr.Read(); (myDr!= null) customerLookup.Add(myDr [「code」],myDr [「customerText」]); myDr.Read(); } – jdweng

回答

3

你可以通過閱讀器返回的行中循環:

var customerLookup = new Dictionary<string, string>(); 
using (var reader = myLookup.ExecuteReader()) 
{ 
    while (reader.Read()) 
    { 
     customerLookup[(string)reader["code"]] = (string)reader["customerText"]; 
    } 
} 

你應該知道,如果有任何重複的代碼,隨後的碼值將覆蓋在字典以前的。如果您希望在這種情況下引發異常,您可以使用customerLookup.Add()

0

你不僅可以,但你絕對應該。正如你所展示的那樣,代碼顯示了對.NET如何工作的完整知識缺乏。

我提出的一些代碼可能被認爲是「矯枉過正」,但它確實證明了一些最佳實踐。

Dictionary<string, string> customerLookup = new Dictionary<string, string>(); 
using (var reader = myLookup.ExecuteReader()) 
{ 
    int ordinalCode = reader.GetOrdinal("code"); 
    int ordinalCustomerText = reader.GetOrdinal("customerText"); 
    while (reader.Read()) 
    { 
     //this code assumes the values returned by the reader cannot be null 
     customerLookup.Add(reader.GetString(ordinalCode), reader.GetString(ordinalCustomerText)) 
    } 
}