将查询结果存储在字典中

本文关键字:字典 存储 查询 结果 | 更新日期: 2023-09-27 18:18:39

我有使用c#开发Windows移动应用程序的问题,我试图用3个查询工作。我想把所有查询结果收集到Dictionary中。

可以不循环地收集它吗?

就像我的代码:

string query= "select distinct nameProduct, price from product";
SqlCeCommand cmd = new SqlCeCommand(sql, dbConn);
Dictionary production = new Dictionary<string, int>();

我如何从我的查询中设置这个结果,因为我在一个进程中有3个这样的查询,数据超过10,000。

@John桑德斯:当我尝试这个,我得到错误"{"没有数据存在的行/列。"}",但实际上当我尝试在SQL服务器查询仍然运行良好。production[(string)reader["nameProduct"]] = (int)reader["price"];

@Johnny:不幸的是,这个项目是在VS2005中构建的,不支持union和join语句。

将查询结果存储在字典中

Dictionary production = new Dictionary<string, int>();
string query= "select distinct nameProduct, price from product";
using (SqlCeCommand cmd = new SqlCeCommand(sql, dbConn))
{
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            production[(string)reader["nameProduct"]] = (int)reader["price"];
        }
    }
}

不带循环。注意我还没有试过:

production =
    reader.Cast<IDataRecord>()
          .ToDictionary(
              record => (string)record["nameProduct"], 
              record => (int)record["price"]);

这是从数据库中获取数据并将数据存储在字典中的简单方法

Dictionary<int, string>emp = new Dictionary<int, string>();
OleDbCommand cmd = new OleDbCommand("select empId,Name from Employee where ORDER BY empId DESC", con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
    while (dr.Read())
    {
         emp.Add(Convert.ToInt32(dr["empId"]), dr["Name"].ToString());                
    }                    
}
foreach (KeyValuePair<int, string> em in emp)
{
    Console.WriteLine(em.Key.ToString() + " = " + em.Value);
}

您可以使用DataAdapter转换数据表。方法将DataTable)结果填充到dictionary中。

string query= "select distinct nameProduct, price from product";
SqlCeConnection conn = new SqlCeConnection("Data Source = your file.sdf");
SqlCeCommand selectCmd = conn.CreateCommand();
selectCmd.CommandText = query;
SqlCeDataAdapter adp = new SqlCeDataAdapter(selectCmd);
DataTable dt=new DataTable();
adp.Fill(dt);
Dictionary<string, int> result = (from row in dt.AsEnumerable()
                          select new KeyValuePair<string, int>
                          (row.Field<string>("nameProduct"), row.Field<int>("price")))
                          .ToDictionary(p=>p.Key,p=>p.Value);
 foreach (var t in result)
  {
    Console.WriteLine(t.Key + " " + t.Value);
  }

几点。

1。我认为你可以在你的查询中使用"联合所有"。2.如果你有超过10000行记录,特别是在移动设备上,我建议你只加载那些你需要的数据,你可以在一个屏幕上显示,而不是读取所有。