Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create a deck of Cards using foreach

This is a homework assignment FYI. And thanks for at least looking at this.

So we're learning about enums, List<>, IComparable<T> and structs, and we're creating a deck of cards. I have a Card Struct, that says to create a card, it needs a rank and suit. I have enums for both.

I'm having trouble with the NewDeck() method.

We were given the method header to use, and given a TIP to "use the static method GetValues to loop through all Rank Enumerators".

We were also given the foreach loop. We're not supposed to call a sort, because looping through all the ranks should create a list already sorted.

I'm having trouble knowing how to add Cards to the deck. To add the Card, I would think I might use Card.Add, but it's not showing up in code completion, and it's not an option, and I'm not sure why. Here's the code for my Cards Struct-

    namespace Cards
{
    struct Card : IComparable<Card>
    {
        public Suit Suit { get; private set; }
        public Rank Rank { get; private set; }
        public Card(Suit suit, Rank rank) :
            this()
        {
            this.Suit = suit;
            this.Rank = rank;
        }
        public override string ToString()
        {
            return string.Format("{0} {1}", (Char)this.Suit, this.Rank);
        }

        public int CompareTo(Card other)
        {
            return Rank.CompareTo(other.Rank);
        }
    }

    public enum Suit { Spades = 9824, Clubs = 9827, Diamonds = 9830, Hearts = 9829 }

    public enum Rank { Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };
}

And here's the code for my newDeckMethod()

public static List<Card>  NewDeck()
        {
            foreach (Cards.Rank r in Enum.GetValues(typeof(Rank)))
               //Card.Add           

        }
like image 920
Cthanatos Avatar asked Feb 13 '14 19:02

Cthanatos


Video Answer


2 Answers

You need to create a list; right now your NewDeck() method doesn't define one.

public static List<Card> NewDeck() {
    List<Card> deck = new List<Card>();
    foreach (Cards.Rank r in Enum.GetValues(typeof(Rank))) {
        foreach (Cards.Suit s in Enum.GetValues(typeof(Suit))) {
            deck.Add(new Card(s, r));
        }
    }

    return deck;
}
like image 87
James Cronen Avatar answered Sep 30 '22 01:09

James Cronen


for extra credit you can use LINQ

private static IEnumerable<Card> NewDeck()
{
    IEnumerable<Suit> suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();
    IEnumerable<Rank> ranks = Enum.GetValues(typeof(Rank)).Cast<Rank>();

    return from r in ranks from s in suits select new Card(s, r);
}

and if you need it as a List<Card> you can call ToList() on the return value.
To sort the other way, just move from r in ranks after from s in suits

like image 31
default Avatar answered Sep 30 '22 01:09

default