1

I am trying to find a more efficient way to read values out of an array of sructs and convert them to something more meaningful, like 'C' is stored in the array and I would like it to be returned as "Clubs", below is what I have so far and it is very inefficient.

   public static void DisplayHandData(Card[] data)
    {
        Console.WriteLine();
        //test values loaded into array in correct positions
        Console.WriteLine("** Values in array **");
        //read values out to check against if statements
        for (int records = 0; records < data.Length; records++)
        {
            Console.WriteLine(data[records].suit);
            Console.WriteLine(data[records].value);
        }
        DrawBlankLine();
        DrawLine();
        DrawBlankLine();
        Console.WriteLine("** Values in suit **");

        if (data[0].suit == 'C')
        {
            string suit = "Clubs";
            Console.WriteLine("Card 1: {0} of {1}", data[0].value, suit);
        }
        else if (data[0].suit == 'D')
        {
            string suit = "Diamonds";
            Console.WriteLine("Card 1: {0} of {1}", data[0].value, suit);
        }
        else if (data[0].suit == 'H')
        {
            string suit = "Hearts";
            Console.WriteLine("Card 1: {0} of {1}", data[0].value, suit);
        }
        else if (data[0].suit == 'S')
        {
            string suit = "Spades";
            Console.WriteLine("Card 1: {0} of {1}", data[0].value, suit);
        }
        else

I will also need to do the same for data[0].value as aces are stored as a value of 14, kings 13 etc..

Any help would be appreciated.

Coop1979
  • 27
  • 5

1 Answers1

2

You could use a dictionary:

private static Dictionary<char, string> suitDictionary = new Dictionary<char, string>
{
    { 'C', "Clubs" },
    { 'H', "Hearts" },
    // ...
}

Then you can obtain the name by accessing the key of the suit:

string suitName = suitDictionary[data[0].suit];
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • How would this work for the values like Ace, King etc in the struct under .value? – Coop1979 Sep 13 '15 at 13:03
  • You don't show the `Card` class so I don't know `value`'s type, but you could create a separate dictionary to hold the card values. – CodeCaster Sep 13 '15 at 13:04
  • struct is ` public struct Card { public char suit;//'C'- Clubs, 'D'-Diamonds,'H'- Hearts //and 'S'- Spades public int value;//2-14 – for 2-10, Jack, Queen, King, Ace }` – Coop1979 Sep 13 '15 at 13:11
  • I am missing something as I now have an error: object reference is require when trying to access the suitName – Coop1979 Sep 13 '15 at 13:26
  • Yeah you need to declare the dictionary as `static` as you're calling it from a static method. – CodeCaster Sep 13 '15 at 13:30