2010-03-29 25 views
13

Tôi có một truy vấn SQL đơn giản (sử dụng SqlCommand, SqlTransaction) trong .NET 2.0 trả về một bảng các cặp số nguyên-chuỗi (ID, Tên). Tôi muốn đưa dữ liệu này vào một từ điển như Dictionary<int, string>.Kết quả lệnh SQL từ điển C# .NET 2.0

Tôi có thể nhận được kết quả vào một DataTable, nhưng thậm chí lặp lại nó, tôi không chắc chắn làm thế nào để làm việc gõ và tất cả những thứ đó. Tôi cảm thấy như thế này phải là một vấn đề phổ biến nhưng tôi đã không tìm thấy bất kỳ giải pháp tốt.

Xin cảm ơn trước.

+0

Cảm ơn đã sửa. Hoàn toàn có ý định đặt các loại ... từ điển như từ điển, lol. – Joel

Trả lời

13

Bạn có thể thử một cách tiếp cận tương tự như sau, điều chỉnh tuy nhiên bạn đang Looping trên kết quả của bạn:

Dictionary<int, string> dictionary = new Dictionary<int, string>(); 
using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
    connection.Open(); 

    using (SqlCommand command = new SqlCommand(queryString, connection)) 
    { 
     using (SqlDataReader reader = command.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       dictionary.Add(reader.GetInt32(0), reader.GetString(1)); 
      } 
     } 
    } 
} 

// do something with dictionary 

Các SqlDataReader.GetInt32 methodSqlDataReader.GetString method sẽ đại diện cho các chỉ số IDName cột, tương ứng.

0
IDictionary<int, string> dict = new Dictionary<int, string>(); 
    DataTable mydata = new DataTable("hey"); 

    foreach (DataRow item in mydata.Rows) 
{ 
    dict.Add(item["id"], item["name"]); 
} 
1

Bạn có thể làm như thế này.

// Define your Dictionary 
IDictionary<int,string> dictionary = new Dictionary<int,string>(); 

// Read your dataTable 
foreach(DataRow row in dataTable.Rows) {  
     // Add Id and Name respectively 
     dictionary.Add(int.parse(row[0].ToString()),row[1].ToString())   
} 
0

tôi đã không gõ này trong visual studio, do đó bạn có thể cần phải thực hiện những thay đổi nhỏ để làm cho nó chạy ...

Dictionary(int key,string value) dictionary = new Dictionary<int key,string value>(); 

foreach(DataRow row in DataTable.Rows) 
{ 
    //null check?? 
    dictionary.add(Convert.toInt(row[0]),row[1].toString()); 
} 

thử mà ... xem giúp.

11

Bạn có thể gửi trả lại như một DataReader, và xây dựng từ điển sử dụng LINQ:

Dictionary<int, string> dictionary; 
using (SqlCommand command = new SqlCommand(queryString, connection)) 
using (SqlDataReader reader = command.ExecuteReader()) { 
    dictionary = reader.Cast<DbDataRecord>() 
         .ToDictionary(row => (int)row["id"], row => (string)row["name"]); 
} 
Các vấn đề liên quan