繁体   English   中英

C#-在有3个字符的情况下拆分字符串,并将值添加到字典中

[英]C# - Splitting the string when there are 3 chars and adding the values to the dictionary

我有一个像这样的字符串:

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

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

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

我不明白在两种情况下都出现错误时,我怎么想用'\\ n'分割字符串,然后用“-”分割字符串?

您需要拆分并清除空条目。
您可以分割为'-' ,而无需分割为" - "
然后,按和求和以获得总字典

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));

这是一个非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;
            }
        }

你有两个问题。

问题1:

如何在此处拆分多个字符: 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM