您没有提到您使用什么技术来执行查询,所以我假设您使用的是一种不会自动映射到类的基本技术。
这很容易做到。你要做的就是:
- 遍历您收到的每一行
KeyValuePair
使用适合列的类型创建一个新对象(通常是string, string
或int, string
)
- 将 的值设置为
KeyValuePair
您从阅读器读取的每一列的值。
- 如果您想对后者做其他事情,请尝试在迭代期间
KeyValuePair
将其添加到 aList<KeyValuePair>
编辑好的,所以根据您的编辑,我猜您是新手。您提到您正在使用 DB2。您没有明确说明您使用哪个库从 DB2 中读取数据,因此我假设它是 IBM 提供的库。我将根据 IBM 的DB2DataReader 类文档提供信息。
以下应该有效(前提是我没有输入错误)。我在此过程中包含了一些评论以提供帮助:
// this variable will have the data read from the server after all is said and done
List<KeyValuePair<int, string>>> data = new List<KeyValuePair<int, string>>();
// create the connection (replace connection string as necessary)
using (DB2Connection conn = new DB2Connection("database connection string"))
{
// specify the query, create and open the command object
string qry = "Select distinct Value, Descrip from cool";
DB2Command cmd = new DB2Command(qry, conn);
conn.Open();
// calling ExecuteReader() sends the query to the database and starts
// the process of reading the data
using(DB2DataReader read = cmd.ExecuteReader())
{
// you have to call Read() for every row. It will return false if there
// are no more rows left
while(read.Read())
{
// calling the various Get methods is how you get the data out of the reader
// note that you pass in the index of the column for each call
int intVal = read.GetInt32(0);
string strVal = read.GetString(1);
// now you're ready to create your KeyValuePair object
KeyValuePair<int, string> tmp = new KeyVauePair<int, string>(intVal, strVal);
// And add it to the list we defined at the start of this
data.Add(tmp);
}
}
}
// and now we've got all of the data from your query wrapped up into a nice list
// called 'data'. Do with it whatever you planned