通过字典迭代foreach

时间:2017-09-26 11:58:14

标签: c# console-application

有没有办法迭代这个循环并且:

var resAndNumber = new Dictionary<int, int>();
for (int i = 0; i < numberRepeats; i++)
{

    for (int n = 0; n < numberDice; n++)
    {

        rolledResult1 += diceRandomGenerate.Next(1, 7);
    }

    //if the sum was not thrown, entry in the dictionary
    if (!resAndNumber.ContainsKey(rolledResult1))
    {
        resAndNumber[rolledResult1] = 0;
    }

    // bisherige  Anzahl für diese Summe hochzählen
    resAndNumber[rolledResult1]++;
}
  • 让控制台的输出可以用一个foreach完成,我正在尝试 了解。 在我陷入死胡同之前,我仍然对基础知识很古怪 - 你能给我任何建议吗?

为了满足问题/目标,允许用户决定要模拟多少骰子。 谢天谢地,c#starter。

The output may look like this

2 个答案:

答案 0 :(得分:2)

Dictionary<T,S>实现了IEnumerable<KeyValuePair<T, S>>,因此可以枚举它:

foreach (var kv in dic) {
  Console.WriteLine($"({kv.Key}, {kv;.Value})");
}

但是,跟踪每个结果的滚动数量的整个想法可以通过数组更容易地跟踪(其中条目将默认为零):

var results = new int[6*diceCount + 1];
// Will ignore indicies 0 to diceCount-1 as easier than using
// non-zero based arrays.

for (var roll = 1; roll <= rollCount; ++roll) {
  var rollResult = Enumerable.Range(0, diceCount)
                             .Select(x => diceRandomGenerate.Next(1, 7))
                             .Sum();
  results[rollResult]++;
}

for (var roll = diceCount; roll <= diceCount*6; ++roll) {
  Console.WriteLine($"{roll:d2} " + new String('*', results[roll]));
}

答案 1 :(得分:0)

这样的东西?:

foreach (var keyValuePair in resAndNumber)
{
    Console.WriteLine($"Die eye {keyValuePair.Key} for the 1. die was {keyValuePair.Value} ties thrown");
}

请注意,您不会存储未滚动的结果,结果将按照首次滚动的顺序排列。因此,如果你滚动1,6,3,6,1,3,3,结果将是(1,2),(6,2)和(3,3)。

您可能希望首先填写字典:

var resAndNumber = new Dictionary<int, int> {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};

然后你可以检查结果是否已经在字典中。

示例:

var resAndNumber = new Dictionary<int, int> {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};

resAndNumber[1]++;
resAndNumber[6]++;
resAndNumber[3]++;
resAndNumber[6]++;
resAndNumber[4]++;

foreach (var keyValuePair in resAndNumber)
{
    Console.WriteLine($"Die eye {keyValuePair.Key} for the 1. die was {keyValuePair.Value} ties thrown");
}