【问题标题】:How does a Key Value Pair handle an exact match to a key that already exists?键值对如何处理与已经存在的键的完全匹配?
【发布时间】:2013-06-22 11:01:41
【问题描述】:

我有一个要插入到字典中的集合,并且有些值已经输入到 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);

    }

}

【问题讨论】:

  • 字典不能有重复的键。
  • 你能添加示例源代码吗?
  • 您可能需要一个MultiMap aka MultiDictionary,它可以使用相同的密钥处理多个项目。如果是这样,请在此处查看答案:stackoverflow.com/a/380601/106159 或者,您可以使用Dictionary&lt;List&lt;YourType&gt;&gt;(例如此处提到的:stackoverflow.com/a/3850989/106159
  • 添加了代码。对不起,它可能看起来很可怕。我永远无法得到正确的格式。
  • @SLaks - 我没有说字典有重复的键。我问字典是否出现重复,键和值会发生什么。

标签: c# keyvaluepair


【解决方案1】:

字典是一对一的映射,如果你需要一对多的映射,你可以创建一个Lookup

Adding 复制到字典将导致 ArgumentException

【讨论】:

  • 只有调用 Add 时才会出错,调用 TryAdd 时只会返回 false。我们需要查看您的添加代码以提供更多帮助。
【解决方案2】:

它确实会覆盖。如果您想将价值添加到现有的,我相信您正在寻找:

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

// or

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

您必须先检查它是否存在,如果存在,则添加值并重新插入到字典中。如果不存在,可以正常设置。

注意这里的线程安全 - 如果您的字典是通过多个线程访问的,此代码可能会使您的字典失控。

【讨论】:

  • 谢谢,我想这就是我要找的。​​span>
【解决方案3】:

如果您只想在进行过程中添加值,那么您需要 Dictionary&lt;String,List&lt;String&gt;&gt; 而不是说 Dictionary&lt;String,String&gt; 而不是仅仅调用 add 类似的东西

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

无论如何都是一种方法。

【讨论】:

  • 我认为你有一些语法问题。
  • 我发现并修复了一个。识别另一个的奖励棒棒糖。
猜你喜欢
  • 1970-01-01
  • 2017-05-10
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多