1

I have a collection that I am inserting into the Dictionary and there are values that have already been entered into the KVPs. Say I already have a key of "4000" and the value comes up again, what happens to the value? Does it add the value of the key instance to the value that already exists for that key? Does it over write the value?

If it over writes, how can I add the values as they iterate through the collection of values?

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);

    }

}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
Markpelly
  • 37
  • 1
  • 7
  • 1
    Dictionary cannot have duplicate keys. – SLaks Jun 25 '13 at 15:03
  • Could you add example source code? – Pieter van Ginkel Jun 25 '13 at 15:04
  • You might want a `MultiMap` aka `MultiDictionary` that can handle multiple items with the same key. If so, check out the answer here: http://stackoverflow.com/a/380601/106159 Alternatively, you can use a `Dictionary>` (eg as mentioned here: http://stackoverflow.com/a/3850989/106159) – Matthew Watson Jun 25 '13 at 15:08
  • Added Code. I'm sorry it probably looks horrible. I can never get the formatting correct. – Markpelly Jun 25 '13 at 15:13
  • @SLaks - I didnt say that the dictionary had duplicate keys. I asked if the Dictionary was presented with a duplicate, what would happen to the key and value. – Markpelly Jun 25 '13 at 15:22

3 Answers3

1

Dictionaries are 1 to 1 maps, if you need a 1 to many map, you can create a Lookup.

Adding a duplicate to a dictionary will result in an ArgumentException.

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • It only errors if you call Add, if you call TryAdd it will just return `false`. We need to see your adding code to provide any more help. – Scott Chamberlain Jun 25 '13 at 15:07
1

It does overwrite. If you want to add the value to the existing one, I believe you're looking for:

if (dict.ContainsKey(key)) {
    dict[key] += newVal;
} else {
    dict[key] = newVal;
}

// or

int currentVal;
dict.TryGetValue(key, out currentVal);
dict[key] = currentVal + newVal;

You have to check to see if it exists first, then if it does, add the values and re-insert to the dictionary. If it doesn't exist, you can set it like normal.

Watch out for thread safety here - if your dictionary is accessed through multiple threads, this code could potentially get your dictionary out of whack.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
1

If you want to just add values as you go along then instead of say Dictionary<String,String> you want Dictionary<String,List<String>> and instead of just calling add something like

if (!myDict.ContainsKey(someKey))
{
   myDict.Add(someKey,new List<String>());
}
myDict[somekey].Add(somevalue);

one way to do it anyway.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39