我有以下代码。我有一个返回多行的Oracle查询。我需要将数据填入字典列表但我有一个问题,即列表总是填充最后一行重复。如何使用每个Oracle行迭代列表。
代码:
var list = new List<string>();
List<Dictionary<String, String>> listDic = new List<Dictionary<String, String>>();
using (var con = new OracleConnection(Config.EDLRDev))
{
var com = con.CreateCommand();
try
{
con.Open();
com.CommandText = "SELECT * FROM edlr_comm_rep_total a where a.dealer_id = 'wb-pos00289' and a.comm_type = 'Activation' ";
//com.Parameters.Add("msisdn", OracleDbType.Char).Value = msisdn;
Dictionary<String, String> objDic = new Dictionary<string, string>();
var reader = com.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
string CommissionDealerId = reader[0].ToString();
string Month = reader[1].ToString();
string DealerCommissionType = reader[2].ToString();
string CommissionCount = reader[3].ToString();
string CommissionAmount = reader[4].ToString();
objDic["CommissionDealerId"] = CommissionDealerId;
objDic["Month"] = Month;
objDic["DealerCommissionType"] = DealerCommissionType;
objDic["CommissionCount"] = CommissionCount;
objDic["CommissionAmount"] = CommissionAmount;
listDic.Add(objDic);
}
}
reader.Close();
}
catch (Exception ex)
{
con.Dispose();
}
con.Dispose();
return listDic;
}
答案 0 :(得分:0)
您需要在循环内初始化objDic
:
var reader = com.ExecuteReader();
if (reader.HasRows) {
while (reader.Read()) {
Dictionary<String, String> objDic = new Dictionary<string, string>(); // MOVED!
string CommissionDealerId = reader[0].ToString();
string Month = reader[1].ToString();
string DealerCommissionType = reader[2].ToString();
string CommissionCount = reader[3].ToString();
string CommissionAmount = reader[4].ToString();
objDic["CommissionDealerId"] = CommissionDealerId;
objDic["Month"] = Month;
objDic["DealerCommissionType"] = DealerCommissionType;
objDic["CommissionCount"] = CommissionCount;
objDic["CommissionAmount"] = CommissionAmount;
listDic.Add(objDic);
}
}
否则你只是重新改变同一个实例。
答案 1 :(得分:0)
您正在使用在while循环之外实例化的相同词典objDic
。您只需要替换循环中每个字典的值。在列表中,您将添加对同一个objDic字典的引用,这就是您有重复项的原因。你需要在while循环中的每次传递中创建一个新的字典。
try
{
con.Open();
com.CommandText = "SELECT * FROM edlr_comm_rep_total a where a.dealer_id = 'wb-pos00289' and a.comm_type = 'Activation' ";
//com.Parameters.Add("msisdn", OracleDbType.Char).Value = msisdn;
var reader = com.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Dictionary<String, String> objDic = new Dictionary<string, string>();
string CommissionDealerId = reader[0].ToString();
string Month = reader[1].ToString();
string DealerCommissionType = reader[2].ToString();
string CommissionCount = reader[3].ToString();
string CommissionAmount = reader[4].ToString();
objDic["CommissionDealerId"] = CommissionDealerId;
objDic["Month"] = Month;
objDic["DealerCommissionType"] = DealerCommissionType;
objDic["CommissionCount"] = CommissionCount;
objDic["CommissionAmount"] = CommissionAmount;
listDic.Add(objDic);
}
}
reader.Close();
}