我正在制作一个"三个或更多"游戏,这意味着我需要让程序识别重复的值(对于一类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]

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

推荐答案

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

  • player1dicerolls组乘score
  • 仅使用一个项目过滤出群组
  • 让我们按分数对小组进行排序
  • 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);

Csharp相关问答推荐

无法使用并行库并行化我的代码

如何使用FastEndpoints和.NET 8 WebAppliationBuilder进行集成测试?

有没有方法让ASP.NET Core模型绑定器使用私有设置器来设置属性?

在. NET Core 8 Web API中,当为服务总线使用通用消费者时,如何防止IServiceProvider被释放或空?"

如何使用ConcurentDictionary属性上的属性将自定义System.Text.Json JsonConverter应用于该属性的值?

只有第一个LINQ.Count()语句有效

Blazorise折线图仅绘制数据集的一部分

C#DateTime.ParseExact不使用特定日期

如何在NET 8最小API中自动记录TypedResults.Stream响应

如何让两个.NET版本不兼容的项目对话?

链接到字典字符串.拆分为(.Key,.Value)

.Net MAUI,在将FlyoutPage添加到容器之前,必须设置添加构造函数导致Flyout和Detail"

如何实现有条件的自定义Json转换器隐藏属性

为什么Azure函数(独立工作进程)索引失败?使用Azure App配置的CosmosDbTrigger绑定失败,未解析为值

如何使用EPPlus C#在单个单元格中可视化显示多行文字

使用未赋值的、传递的局部变量

使用Blazor WebAssembly提高初始页面加载时间的性能

FakeItEasy自动嘲弄内容

为什么连接到Google OAuth2后,结果.Credential为空?

如果图表S批注包含使用LINQ的具有特定名称的批注,我如何签入C#