将SQL命令结果转换为C# .NET 2.0字典

22

我有一个简单的SQL查询(使用SqlCommand、SqlTransaction)在.NET 2.0中返回一个整数-字符串对的表格(ID,Name)。我想把这些数据放到一个像Dictionary<int, string>这样的字典中。

我可以把结果放到DataTable中,但即使迭代它,我也不确定如何进行类型转换和所有相关的操作。我感觉这一定是一个常见的问题,但我没有找到任何好的解决方案。

提前致谢。


感谢您的编辑。我完全打算将类型放入像字典这样的字典中,哈哈。 - Joel
5个回答

20
你可以尝试类似这样的方法,根据你当前循环结果的方式进行调整:
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

SqlDataReader.GetInt32方法SqlDataReader.GetString方法分别代表IDName列的索引。


15
你可以将其作为 DataReader 返回,并使用 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"]);
}

1
你可以这样做。
// 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
    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

我没有在Visual Studio中输入这个,所以你可能需要做一些小的更改才能运行它...

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

试试那个...看看是否有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接