You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC迁移后遇重复键报错:An item with the same key has already been added

Fixing "An Item with the Same Key Has Already Been Added" Error in MVC Donation Processing

Hey there! Let's figure out why your donation amount aggregation code is throwing that "An Item with the Same Key Has Already Been Added" error now that you've moved it from WinForms to MVC. The root issue here is almost certainly that your dictionary is trying to add a key that already exists—something that didn't happen in your WinForms environment (probably because you never received a text with duplicate account entries until now).

First, Let's Break Down the Problem

Your code splits incoming text strings like th 20.00, bf 10.00 into a dictionary to sum amounts per account. The Dictionary<TKey, TValue> in C# doesn't allow duplicate keys, so if a text comes through with the same account listed twice (like th 20.00, th 15.00), the Add() method will throw that exact error.

Here's How to Fix It

Instead of using Add() directly, you need to check if the account key already exists in the dictionary. If it does, you'll update the existing amount by adding the new value. If not, you'll add the key to the dictionary.

Here's a revised version of your processing code with safeguards:

// Initialize dictionary (optional: use StringComparer to ignore case for accounts like "TH" vs "th")
var donationTotals = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);

// Split the input string, removing any empty entries from extra commas
var accountEntries = smsContent.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

foreach (var entry in accountEntries)
{
    var trimmedEntry = entry.Trim();
    // Skip any empty or whitespace-only entries
    if (string.IsNullOrWhiteSpace(trimmedEntry)) continue;

    // Split each entry into account and amount, removing extra spaces
    var parts = trimmedEntry.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    // Skip entries that don't have exactly two parts (account + amount)
    if (parts.Length != 2)
    {
        // Log this invalid entry for debugging later if needed
        continue;
    }

    var account = parts[0].Trim();
    // Try to parse the amount to avoid format errors
    if (!decimal.TryParse(parts[1].Trim(), out var donationAmount))
    {
        // Log invalid amount format here
        continue;
    }

    // Check if the account already exists in the dictionary
    if (donationTotals.TryGetValue(account, out var existingTotal))
    {
        // Update the total by adding the new donation
        donationTotals[account] = existingTotal + donationAmount;
    }
    else
    {
        // Add the new account and amount
        donationTotals.Add(account, donationAmount);
    }
}

Additional Troubleshooting Tips

  • Log incoming SMS content: Capture the exact string your MVC app is receiving. This will confirm if duplicate accounts are actually present in the text, or if your splitting logic is creating unintended duplicate keys (like from extra spaces or formatting quirks).
  • Check for duplicate requests: Sometimes APIs can resend messages if they don't get an immediate response. Make sure your MVC endpoint is idempotent (can handle duplicate requests without breaking) by tracking message IDs if the texting API provides them.
  • Validate input rigorously: The code above includes checks for invalid entries and bad amount formats—this will prevent unexpected errors beyond just duplicate keys.

内容的提问来源于stack exchange,提问作者Justin Budd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:25:35