【问题标题】:C# - Splitting the string when there are 3 chars and adding the values to the dictionaryC# - 当有 3 个字符时拆分字符串并将值添加到字典中
【发布时间】:2017-03-30 18:20:05
【问题描述】:

我有一个这样的字符串:

var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";

它是动态创建的,所以这个只是为了举例。数字表示订购了多少份。我需要以食物的名称作为键将其拆分为字典,并计算订购了多少份,这将是一个值。

我试过这个分割字符串,首先是 '\n' 然后是 ' - ':

count = totalOrders.Split('\n').ToDictionary(item => item.Split(" - ")[0], item => int.Parse(item.Split(" - ")[1]));

但我收到一个错误“无法从字符串转换为字符。我必须使用双引号,因为“-”有 3 个字符(2 个空格和一个破折号)并且它不被识别为字符。

另外,我认为问题出在我开始添加食物时,因为考虑到食物不止一次出现,它会报告键不会是唯一的。如何解决?

编辑:

当我尝试这个时:

string[] countOrders = totalOrders.Split('\n');
string[] parts1 = countOrders.Split(new string[] { " - " }, StringSplitOptions.None);

我在 .Split 处遇到错误

'string[]' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'string[]' could be found

如果我尝试这个“字符串 countOrders =”(所以没有 [])我得到

Cannot implicitly convert type 'string[]' to 'string'

我不明白我应该如何将字符串拆分为“\n”,然后再拆分为“-”,这两种情况下都会出现错误?

【问题讨论】:

  • 只是看你可能需要添加字符串拆分选项删除空到你的拆分方法调用,因为你得到一个额外的项目,其中没有任何内容。如果您的 int.Parse 异常,则该条目可能是原因。所以你的拆分电话看起来像这样 totalOrders.Split(new char[] { '\n' },StringSplitOptions.RemoveEmptyEntries)
  • Brown Bread 也在那里两次,所以你会得到重复的 Key Exception。
  • 下面的答案介绍了如何使用拆分多个字符。我确实添加了它,因为他的回答在我发布之前就来了。​​

标签: c# string dictionary split count


【解决方案1】:

您需要拆分并删除空条目。
您可以在'-'上拆分,无需在" - "上拆分
然后,分组和求和得到一个总字典

Dictionary<string, int> count =
    totalOrders.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries)
        .Select(item => item.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries))
        .Select(arg=> new {Key = arg[0].Trim(), Val=  int.Parse(arg[1].Trim())})
        .GroupBy(arg=>arg.Key)
        .ToDictionary(g => g.Key, g => g.Sum(arg=>arg.Val));

【讨论】:

    【解决方案2】:

    这是一个非 linq 选项,因为它是 OP 要求的,我个人更喜欢 linq 方式,但是这会产生相同的结果

     var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";
     var DictionaryHolder = new Dictionary<string, int>();
     //Split initial string into array and remove empties
     string[] initialArray = totalOrders.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
    
            foreach (var item in initialArray)
            {
                // Get the string Key or Entree
                string key = item.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
                //  Get the Count of Portions
                int count = int.Parse(item.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[1].Trim());
    
                // check if Dictionary has the key already if not add it
                if (!DictionaryHolder.ContainsKey(key))
                {
                    DictionaryHolder.Add(key, count);
                }
                else
                {
                    // If the dictionary already had that key increase portion count by amount ordered.
                    DictionaryHolder[key] = DictionaryHolder[key] + count;
                }
            }
    

    【讨论】:

      【解决方案3】:

      你有两个问题。

      问题一:

      这里回答了如何按多个字符分割:https://stackoverflow.com/a/1254596/2654498。下面的代码直接来自那里。

      string input = "abc][rfd][5][,][.";
      string[] parts1 = input.Split(new string[] { "][" },StringSplitOptions.None);
      

      问题 2:

      您需要检查字典以查看 Food 是否已作为键存在。如果是这样,那么您需要简单地更新该食物的价值。如果它不作为键存在,请将其作为新项目添加到您的字典中。

      if (!foodDict.ContainsKey(food))
      {
           foodDict.Add(food, qty);
      }
      else
      {
           foodDict[food] += qty;
      }
      

      【讨论】:

      • @MarkWest 没问题。基本上,只需使用ContainsKey 函数。如果它不存在(上面的if 条件,则添加它,因为它是一种新食物)。如果存在(else 以上条件,则只需更新值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多