我有一个我正在插入字典的集合,并且已经输入了KVP中的值。假设我已经有一个“4000”的键并且值再次出现,该值会发生什么变化?它是否将键实例的值添加到该键已存在的值中?是否过度写入了值?
如果它过度写入,我如何在迭代值集合时添加值?
public class AccountBalance
{
public decimal balance { get; set; }
public bool balancesheetact { get; set; }
public AccountBalance()
{
balance = 0;
balancesheetact = false;
}
}
Dictionary<string, List<AccountBalance>> balances = new Dictionary<string, List<AccountBalance>>();
var jentries = from je in gl.JEHeaders
where je.ped_int_id >= beginperiod && je.ped_int_id <= endperiod
orderby je.ped_int_id
select je;
bool isBalanceSheet;
foreach (JEHeader header in jentries)
{
foreach (JEDetail entry in header.JEDetails)
{
string subAccount = entry.ChartOfAccounts.acc_ext_id.Trim();
string key = subAccount.Remove(0, 4);
if (entry.ChartOfAccounts.acc_ty >= 15320 && entry.ChartOfAccounts.acc_ty <= 15322)
isBalanceSheet = true;
else
isBalanceSheet = false;
AccountBalance value = null;
if (!balances.ContainsKey(key))
{
List<AccountBalance> account_balances = new List<AccountBalance>();
// for (int i = 0; i < 12; ++i)
for (int i = 0; i < 14; ++i)
account_balances.Add(new AccountBalance());
balances.Add(key, account_balances);
}
// value = balances[key][header.ped_int_id % beginperiod];
value = balances[key][(header.ped_int_id % beginperiod) + 1];
/// NEW
if (header.ped_int_id == 637)
value = balances[key][0];
/// end NEW
if (entry.jnl_pst_deb_at != null)
value.balance += entry.jnl_pst_deb_at.HasValue ? entry.jnl_pst_deb_at.Value : 0;
if (entry.jnl_pst_crd_at != null)
value.balance -= entry.jnl_pst_crd_at.HasValue ? entry.jnl_pst_crd_at.Value : 0;
if (isBalanceSheet == true)
value.balancesheetact = true;
else
value.balancesheetact = false;
}
}
balances = balances.OrderBy(kvp => kvp.Key).ToDictionary(xyz => xyz.Key, xyz => xyz.Value);
int row = 0;
decimal ytdbalance;
foreach (KeyValuePair<string, List<AccountBalance>> account in balances)
{
row++;
//string subAccount = account.Key.Remove(0, 4);
workbook.AddCell(row, 0, account.Key);
ytdbalance = 0;
bool BS = account.Value[0].balancesheetact;
for (int i = 1; i < 13; ++i)
{
ytdbalance = ytdbalance + account.Value[i].balance;
if (BS == true)
workbook.AddCell(row, i + 1, ytdbalance);
else
workbook.AddCell(row, i + 1, account.Value[i].balance);
}
}
答案 0 :(得分:1)
字典是1对1地图,如果您需要1对多地图,则可以创建Lookup。
Adding复制到字典会产生ArgumentException。
答案 1 :(得分:1)
它会覆盖。如果您想将值添加到现有值,我相信您正在寻找:
if (dict.ContainsKey(key)) {
dict[key] += newVal;
} else {
dict[key] = newVal;
}
// or
int currentVal;
dict.TryGetValue(key, out currentVal);
dict[key] = currentVal + newVal;
您必须先检查它是否存在,如果存在,请添加值并重新插入字典。如果它不存在,您可以像平常一样进行设置。
在这里注意线程安全 - 如果你的字典是通过多个线程访问的,那么这段代码可能会让你的字典无法解决。
答案 2 :(得分:0)
如果您只是想随意添加值,而不是说Dictionary<String,String>
,而不是只需要调用添加类似
<String,List<String>>
if (!myDict.ContainsKey(someKey))
{
myDict.Add(someKey,new List<String>());
}
myDict[somekey].Add(somevalue);
无论如何要做到这一点。