已添加具有相同键的项目 mvc

an item with the same key has already been added mvc

您好,我正在尝试将字符串中的结果拆分到字典中,以便将数字相加。这是从短信收到的信息 api 客户将在一个帐户中发短信 + 他们想要捐赠的金额,多个帐户用逗号分隔 ex th 20.00,bf 10.00 等

当我 运行 它工作的代码在 windows 表单中找到但是当我转换到 MVC 时我得到错误 "an item with the same key has already been added" 我知道这意味着它复制了一个密钥。我尝试在 foreach 循环中输入 if 语句:

    if(!tester.containsKey(j){} 

但这并不总能解决问题,并产生了关于超出范围的新错误。以下是我当前的代码:

    public ActionResult register(text2give reg)
    {
        string body = reg.body;
        try
        {
            var items = body.Split(',');

            Dictionary<string, float> tester = new Dictionary<string, float>();
            var j = 0;
            var total = 0f;
            while (j < body.Length)
            {

                foreach (var item in items)
                {

                    var s = item.Trim().Split(' ');
                    tester.Add(s[0], float.Parse(s[1]));
                    total += float.Parse(s[1]);
                    j++;

                }
            }
            ViewBag.total = total;
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
        return View(reg);
    }

s[0] 是重复键不是 j。您需要使用以下内容

var s = item.Trim().Split(' ');
if(!tester.containsKey(s[0]){
    tester.Add(s[0], float.Parse(s[1]));
    total += float.Parse(s[1]);
    j++;
} 

您可能会得到重复的数据,请小心忽略键,因为您可能确实需要这些数据。我只是向您展示如何抑制错误。

你的代码没问题,但它做了很多假设:

  • 假设 body 正确拆分
  • 它假定所有项目都是唯一的(显然它们不是,因此出现错误)
  • 它假定每个项目中有两个元素(不是,因此出现 indexOutOfRangeException)

以下是我编写此代码以确保它正确防范这些情况的方式:

public ActionResult register(text2give reg)
{
    string body = reg.body;
    try
    {
        var items = body.Split(',');
        var splitItems = items.Select(i => i.Split(' ')).ToList();

        var itemsWithTwoValues = splitItems.Where(s => s.Length == 2);

        var uniqueItems = itemsWithTwoValues.GroupBy(s => s[0])
                                            .Where(g => g.Count() == 1)
                                            .SelectMany(g => g);

        var tester = uniqueItems.ToDictionary(s => s[0], s => float.Parse(s[1]));

        var total = tester.Sum(s => s.Value);

        ViewBag.total = total;
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
    }
    return View(reg);
}

或者,更短的压缩版本:

public ActionResult register(text2give reg)
{
    string body = reg.body;
    try
    {
        var tester = body.Split(',')                            // Split the initial value into items
                         .Select(i => i.Split(' '))             // Split each item into elements
                         .Where(s => s.Length == 2)             // Take only those that have 2 items
                         .GroupBy(s => s[0])                    // Group by the key
                         .Where(g => g.Count() == 1)            // Remove all those that have a duplicate key
                         .SelectMany(g => g)                    // Ungroup them again
                         .ToDictionary(s => s[0], 
                                       s => float.Parse(s[1])); // Create a dictionary where the first item is the key and the second is the parsed float

        var total = tester.Sum(s => s.Value);

        ViewBag.total = total;
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
    }
    return View(reg);
}