Search code examples
c#listlinqclasscollections

How do I print out the Linq values, that have been added to a List, instead of: "System.Collections.Generic.List`1[System.Int32]" in C#?


I am making a Three Or More game, which means that I need to make the programme recognise repeated values (for a 3 of a kind function).

I have created a Die class that rolls a pseudorandom integer from 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
    }
}

In my Game class, and then in my ThreeOrMore class, I've created an empty list:

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

The for loop is then used to roll the player's dice 5 times, by creating a Die object, and then adds the dice roll to the List:

               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);
               }

And finally, I have used a foreach statement to print out each value of the List, which are then put through a Linq (which should print out the dice numbers that are repeated):

An overflow answer said to try "string.Join()", however that hasn't worked either.

                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);

However, my output is this:

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

Can anyone please help me make the programme print out the repeated values?


Solution

  • Let's solve your problem with a help of Linq, we should

    • group player1dicerolls by scores
    • filter out groups with just one item
    • let's order the groups by score
    • represent each group in Element: Counter: format
    • finally, join these representation with, say, new line delimiter

    For instance:

    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);