Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I loop through IEnumerble<Card> CreateDeck(); and print to the console?

So I recently wrote an algorithm which I posted on stack exchange/code review and it was very well received and I got loads of improvements suggested. I’m new to C# and I don’t really understand the IEnumerable interface.

How do I print to the console my entire deck?

The code below is a method, if I call the method there is nothing else I can do… Or can I?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One of the Methods I was suggested to use is:

public IEnumerable<Card> CreateDeck()
{
  var deck = new List<Card>();

  foreach(var value in Enum.GetValues<CardValue>())
    foreach (var suit in Enum.GetValues<CardSuit>())
      deck.Add(new Card(value, suit));

  return deck;
}

My Enums for Cards

public enum CardValue {Ace, King, Queen, Jack, Ten, Nine, Eight, Seven, Six, Five, Four, Three, Two};
public enum CardSuit {Spades, Clubs, Hearts, Diamonds};

Creating a Card

public struct Card
{
  public CardValue Value { get; }
  public CardSuit Suit { get; }

  public Card(CardValue value, CardSuit suit)
  {
    Value = value;
    Suit = suit;
  }

  public override string ToString()
  {
    return $"{Value} of {Suit}";
  }
}

>Solution :

Just use a simple foreach loop:

foreach (var card in CreateDeck()) Console.WriteLine(card);

This uses the Console.WriteLine(object) overload, that will internally call the ToString() method defined on Card.


As an aside, you could reduce memory usage in your CreateDeck method by using yield return instead of allocating a list:

public IEnumerable<Card> CreateDeck()
{
    foreach (var value in Enum.GetValues<CardValue>())
    {
        foreach (var suit in Enum.GetValues<CardSuit>())
        {
            yield return new Card(value, suit);
        }
    }
}

This way, Cards are created on-demand as you iterate, and immediately become eligible for garbage collection after they leave scope.

If you find that you need a list, you can always do this:

var cards = CreateDeck().ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading