已添加具有相同密钥的项目mvc

时间:2018-03-19 19:26:51

标签: c# asp.net asp.net-mvc asp.net-mvc-4

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

当我运行代码时,它可以在Windows窗体中找到,但是当我转换为MVC时,我得到错误"已经添加了具有相同密钥的项目"我知道这意味着它重复了一把钥匙。我尝试在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);
    }

2 个答案:

答案 0 :(得分:3)

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

  • 假设身体正确分裂
  • 它假设所有项目都是唯一的(显然它们不是,因此错误)
  • 假设每个项目中有两个元素(它不是,因此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);
}

答案 1 :(得分:1)

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++;
} 

您可能会收到重复数据,请小心忽略密钥,因为您可能实际需要数据。我只是告诉你如何抑制错误。