SQL Command Result to Dictionary C# .NET 2.0

后端 未结 5 636
感动是毒
感动是毒 2021-02-01 06:55

I have a simple SQL query (using SqlCommand, SqlTransaction) in .NET 2.0 that returns a table of integer-string pairs (ID, Name). I want to get this data into a dictionary like

相关标签:
5条回答
  • 2021-02-01 07:38

    You could try an approach similar to this, adjusted to however you're currently looping over your results:

    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
    

    The SqlDataReader.GetInt32 method and SqlDataReader.GetString method would represent the ID and Name column indices, respectively.

    0 讨论(0)
  • 2021-02-01 07:39

    You can return it as a DataReader, and construct the dictionary using 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"]);
    }
    
    0 讨论(0)
  • 2021-02-01 07:44

    You can do like this.

    // 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 讨论(0)
  • 2021-02-01 07:51

    i did not type this in visual studio so you might need to make minor changes to make it run...

    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());
    }
    

    try that ... see if that helps.

    0 讨论(0)
  • 2021-02-01 07:57
        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"]);
    }
    
    0 讨论(0)
提交回复
热议问题