简体   繁体   English

如何在C#中将查询保存到字典中?

[英]How to save query into dictionary in c#?

I am using Visual Studio 2012 and C#. 我正在使用Visual Studio 2012和C#。 I have a problem: I want to collect all results of a SQL query into dictionary. 我有一个问题:我想将SQL查询的所有结果收集到字典中。

This is my code: 这是我的代码:

Dictionary<int,List<string>> dic = new Dictionary<int, List<string>>();

string query = "select request_number, service_category ,service_type from enugro.enugro_service_requests_info;";

MySqlConnection connec = new MySqlConnection(strcon);
connec.Open();

MySqlCommand cmd = new MySqlCommand(query,connec);
MySqlDataReader reader = cmd.ExecuteReader();

while(reader.Read())
{
    dic.Add((int)reader["request_number"], {               reader["service_category"], reader["service_type"] });
}

// display result
foreach(var disp in dic)
{
    MessageBox.Show(disp.Key.ToString()+"= "+disp.Value.ToString());
}

As you can see my SQL query returns 3 columns to be retrieved and to store into dictionary. 如您所见,我的SQL查询返回3列以进行检索并将其存储到字典中。 Could you help me? 你可以帮帮我吗?

Since the type of the dictionary values is List<string> , then you need to create a new list for each row and add it to the dictionary like this: 由于字典值的类型为List<string> ,因此您需要为每一行创建一个新列表,并将其添加到字典中,如下所示:

dic
  .Add(
      (int)reader["request_number"],
      new List<string>
      {
          reader["service_category"].ToString(),
          reader["service_type"].ToString()
      });

Consider creating a class to hold the information that you want from each row and use it as the type for the dictionary values. 考虑创建一个类来保存每一行所需的信息,并将其用作字典值的类型。 Such class would look something like this: 这样的类看起来像这样:

public class MyValue
{
    public string ServiceCategory {get;set;}
    public string ServiceType {get;set;}
}

Then you can have your dictionary be of type Dictionary<int, MyValue> which will allow you to do this: 然后,您可以使字典的类型为Dictionary<int, MyValue> ,这将允许您执行以下操作:

dic
  .Add(
      (int)reader["request_number"],
      new MyValue
      {
          ServiceCategory = reader["service_category"].ToString(),
          ServiceType = reader["service_type"].ToString()
      });

Why would you do that? 为什么要这么做? You can create DTO (data transfer object) with properties according to column names in database, and bind query result to it. 您可以根据数据库中的列名称创建具有属性的DTO(数据传输对象),并将查询结果绑定到该DTO。 Then you can return list of DTO objects. 然后,您可以返回DTO对象的列表。 It would be better solution, then complicating with dictionary. 这将是更好的解决方案,然后使字典复杂化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM