计算不添加每个项目,添加为总C#控制台应用程序

时间:2017-11-16 19:44:27

标签: c# console-application

尝试获取数组中每个项目的计数,但是它会添加一个总数。

  Dictionary<string, int> counts = new Dictionary<string, int>() {
          { "HelloWorld", 0},
          { "Hello", 0},
          { "World", 0},
          { "integer", 0},
        };


        foreach (var item in arraylist)
        {
            counts["HelloWorld"] += 1;
            counts["Hello"] += 1;
            counts["World"] += 1;
            counts["integer"] += 1;

        }

        Console.WriteLine("");

        foreach (KeyValuePair<string, int> item in counts)
        {
            Console.WriteLine(item.Key.ToString() + ":" + item.Value.ToString());
        }


        Console.ReadLine();
        }

E.g。输入:1,10

预期产出:

hello: 3
world: 5
helloworld: 1
integer: 11

在dotnet小提琴下面运行以找到问题:

https://dotnetfiddle.net/eKHb5x

3 个答案:

答案 0 :(得分:1)

您需要在foreach循环中使用if语句,即

foreach (var item in arraylist)
{
    if (item.Equals("Hello") )
    {
        counts["Hello"]++;
    }
    else if (item.Equals("World"))
    {
        counts["World"]++;
    }
    else if (item.Equals("HelloWorld"))
    {
        counts["HelloWorld"]++;
    }
    else if (item.Equals("integer"))
    {
        counts["integer"]++;
    }
}

另外,只是一个挑剔,你不需要

item.Key.ToString()

因为键是一个以

开头的字符串
item.Key

应该足够了。

答案 1 :(得分:0)

将您的ArrayList更改为List<string>

当你迭代它时,使用item变量作为词典的键。

        foreach(string item in list) {
            if(counts.ContainsKey(item)) {
                counts[item]++;
            } else {
                counts["integer"]++;
            }
        }

答案 2 :(得分:0)

将数组列表更改为List并执行此操作

foreach(var item in arrayList)
{
    if(counts.Contains(item))
    {
        counts[item]++;
    }
    else if (int.TryParse(item, out var i)) // this is a newish feature and my syntax might be a bit off
    {
        counts["integer"]++;
    }
}

我在手机上这样做了很抱歉,如果有任何拼写错误。我很快就会检查并在笔记本电脑上更正