如何打印已添加到列表中的 Linq 值,而不是 C# 中的“System.Collections.Generic.List`1[System.Int32]”?

问题描述 投票:0回答:1

我正在制作一个三个或更多的游戏,这意味着我需要让程序识别重复值(对于 3 个同类函数)。

我创建了一个 Die 类,它滚动 1-6 之间的伪随机整数:

internal class Die
{
    private static Random random = new Random(); // Creates an instance of a random object using the built-in Random class

    // Roll() method
    public int Roll()
    {
        int diceroll = random.Next(1, 7); // Picks a random integer (1-6) from a list using the random object

        //Console.WriteLine("One dice rolled a "+ diceroll);

        return diceroll; // Assigns a value to the dicevalue property
    }
}

在我的 Game 类中,然后在我的 ThreeOrMore 类中,我创建了一个空列表:

List<int> player1dicerolls = new List<int>();

然后使用 for 循环通过创建 Die 对象来掷玩家的骰子 5 次,然后将掷骰子添加到列表中:

               for (int i = 0; i < 5; i++)
               {
                   Die dice1 = new Die();
                   int x = dice1.Roll();
                   Console.ReadLine();
                   Console.WriteLine($"One dice rolled a {x}");
                   player1dicerolls.Add(x);
               }

最后,我使用了 foreach 语句来打印列表中的每个值,然后将其放入 Linq(它应该打印出重复的骰子数字):

溢出答案说尝试“string.Join()”,但这也不起作用。

                foreach (var value in player1dicerolls.GroupBy(x => x)
                    .Where(g => g.Count() > 1)
                    .Select(y => new { Element = y.Key, Counter = y.Count() })
                    .ToList())
                {
                    Console.WriteLine(player1dicerolls);
                }

                string.Join(", ", player1dicerolls);

但是,我的输出是这样的:

System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]

谁能帮我让程序打印出重复的值吗?

c# list linq class collections
1个回答
0
投票

让我们在 Linq 的帮助下解决您的问题,我们应该

  • player1dicerolls
    ,作者:
    score
    s
  • 过滤掉只有一项的组
  • 让我们按分数对各组进行排序
  • Element: Counter:
    格式代表每个组
  • 最后,用新行分隔符连接这些表示形式

例如:

var report = string.Join(Environment.NewLine, player1dicerolls
  .GroupBy(score => score)
  .Where(group => group.Count() > 1)
  .OrderBy(group => group.Key) 
  .Select(group => $"Element: {group.Key}, Counter: {group.Count()}"));

Console.WriteLine(report);
© www.soinside.com 2019 - 2024. All rights reserved.