C# mvc中已添加具有相同密钥的项

C# mvc中已添加具有相同密钥的项,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,您好,我正在尝试将字符串的结果拆分到字典中,以便将数字相加。这是从短信api收到的信息,客户将在一个帐户中发送短信+他们想要捐赠的金额,多个帐户之间用逗号ex th 20.00、bf 10.00等分隔 当我运行在windows窗体中找到的代码时,但当我转换到MVC时,我得到错误“已添加具有相同密钥的项”,我知道这意味着它复制了一个密钥。我尝试在foreach循环期间输入if语句: if(!tester.containsKey(j){} 但这并不总能解决问题,并产生了一个关于超出范围的

您好,我正在尝试将字符串的结果拆分到字典中,以便将数字相加。这是从短信api收到的信息,客户将在一个帐户中发送短信+他们想要捐赠的金额,多个帐户之间用逗号ex th 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);
    }
public ActionResult寄存器(text2give reg)
{
字符串体=注册表体;
尝试
{
var items=body.Split(',');
字典测试器=新字典();
var j=0;
var总计=0f;
而(j<体长)
{
foreach(项目中的var项目)
{
var s=item.Trim().Split(“”);
tester.Add(s[0],float.Parse(s[1]);
total+=float.Parse(s[1]);
j++;
}
}
ViewBag.total=总计;
}
捕获(例外情况除外)
{
Response.Write(例如ToString());
}
返回视图(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++;
} 

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

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

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

您的代码还可以,但它做出了许多假设:

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

您的代码还可以,但它做出了很多假设:

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

<>代码>正文>代码>考虑使用<代码>测试仪[]/COD>而不是<代码>测试仪。添加< /代码> @ SPLANER,这是通过文本API接收的。假设用户在捐赠中输入文本,该文本的格式为他们希望捐赠的目的地和金额,如果他们想做多个目的地,则每个目的地将由一个公共点分隔。例如ReG.BooS=提供20,15,青年25的内容<代码> Re>体<代码>。考虑使用<代码>测试仪[]/COD>而不是<代码>测试仪。添加< /代码> @ SPLANER,这是通过文本API接收到的。假设用户在捐赠中输入文本,该文本的格式为他们希望捐赠的目的地和金额,如果他们想做多个目的地,则每个目的地将由一个公共点分隔。例如reg.body=提供20、15号楼、25号楼。需要注意的是-
float。如果客户端区域性和服务器区域性格式不匹配,解析可能会崩溃。因此,需要注意确保客户机和服务器之间是相同的(可能使用
CultureInfo.InvariantCulture
)。在这种情况下,由于某种原因,您必须使用
TryParse
,上面的代码并没有将总数相加,它只提取注册表正文中的第一项。我使用缩写的oneTry调试代码并查看字典中的值。如果我使用下面的get,它只捕获正文的第一部分,需要注意的是-
float。如果客户端区域性和服务器区域性格式不匹配,解析可能会崩溃。因此,需要注意确保客户机和服务器之间是相同的(可能使用
CultureInfo.InvariantCulture
)。在这种情况下,由于某种原因,您必须使用
TryParse
,上面的代码并没有将总数相加,它只提取注册表正文中的第一项。我用缩写的oneTry调试代码,看看字典中的值是什么。如果我用下面的get,它只捕获主体TH20的第一部分