KeyValuePair
C#
KeyValuePair<TKey,TValue>的用法。结构体,定义可设置或检索的键/值对。也就是说我们可以通过
它记录一个键/值对这样的值。比如我们想定义一个ID(int类型)和Name(string类型)这样的键/值对,那么可以这
样使用。
/// <summary>
/// 设置键/值对
/// </summary>
///
<returns></returns>
private KeyValuePair<int, string>
SetKeyValuePair()
{
int intKey =
1;
string
strValue = "My value";
KeyValuePair<int, string> kvp = new
KeyValuePair<int, string>(intKey,
strValue);
return
kvp;
}
/// <summary>
/// 获得键/值对
/// </summary>
private void GetKeyValuePairDemo()
{
KeyValuePair<int, string> kvp =
SetKeyValuePair();
int intKey =
kvp.Key;
string
strValue = kvp.Value;
}
如果想使用泛型的话,也是差不多这样子,一般批量读取数据的时候,当只需要读两个字段(Id and Name)时,
如果想不用Model类,并配合泛型使用KeyValuePair,示例:
1、从数据库中读取数据
/// <summary>
/// 获取所有企业的Id(enterprise_id)及英文名 (enterprise_name_eng)
/// </summary>
/// <returns>enterprise_info表中的所有企业
Id及英文名</returns>
public
List<KeyValuePair<long,string>>
GetEnterpriseIdAndNameEn
gList()
{
//enterprise_id键和enterprise_name_eng 对
List<KeyValuePair<long,
string>> lstIdKeyNameEngValue = new
List<KeyValuePair<long,
string>>();
string
cmdText = "select enterprise_id, enterprise_name_eng from
enterprise_info";
using
(OracleDataReader reader =
OracleHelper.ExecuteReader(OracleHelper.OracleConnString,
CommandType.Text, cmdText, null))
{
try
{
MyEventLog.Log.Debug ("cmdText= " + cmdText);
while (reader.Read())
{
KeyValuePair<long, string>
idKeyNameEngValue = new KeyValuePair<long,
string> (
&nbs
p;
reader.IsDBNull(0) ? 0 :
reader.GetInt64(0),
;
reader.IsDBNull(1) ? string.Empty :
reader.GetString(1)
; );
lstIdKeyNameEngValue.Add (idKeyNameEngValue);
}
OracleHelper.DataReaderClose(reader);
}
catch (OracleException e)
{
MyEventLog.Log.Error ("cmdText= " + cmdText);
MyEventLog.Log.Error(e);
throw e;
}
}