SQL Command Result to Dictionary C# .NET 2.0

后端 未结 5 640
感动是毒
感动是毒 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 dictionary = new Dictionary();
    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.

提交回复
热议问题