我正在制作一个"三个或更多"游戏,这意味着我需要让程序识别重复的值(对于一类3的功能).
我创建了一个Die类,它从1-6滚动伪随机integer:
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声明打印出List的每个值,然后将这些值通过Linq(它应该打印出重复的骰子号码):
溢出答案说try "strange.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]
有人能帮我让程序打印出重复的值吗?