0

How can I create a list with a fixed set of entries.

Learning C# and doing an exercise to list all cards in a deck of cards(without jokers). Going to use two foreach loops to print them out.

However I cannot get a default list of the cards(I am overloading the method). Looking at the docs http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx and some examples http://www.dotnetperls.com/list and each element is added in individually.

// from dotnet perls
class Program
{
    static void Main()
    {
    List<string> dogs = new List<string>(); // Example List

    dogs.Add("spaniel");         // Contains: spaniel
    dogs.Add("beagle");          // Contains: spaniel, beagle
    dogs.Insert(1, "dalmatian"); // Contains: spaniel, dalmatian, beagle

    foreach (string dog in dogs) // Display for verification
    {
        Console.WriteLine(dog);
    }
    }
}

I have tried both the Add and Insert methods but cannot create my lists.

// my code
using System;
using System.Collections.Generic;
using System.Linq;

class Deck
{
    static void Main()
    {
        List<string> deck = new List<string>();
        deck.Insert("Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King");
        List<string> colour = new List<string>();
        colour.Add("Hearts", "Diamonds", "Spades", "Clubs");
        foreach (string card in deck)
        {
            foreach(string suit in colour)
            {
                Console.Write(colour + " " + card);
            }
        }
    }
}
3
  • Does your code even compiling without errors? Commented Jul 20, 2014 at 11:37
  • Duplicate, see this: stackoverflow.com/a/3139278/1726419 Commented Jul 20, 2014 at 11:39
  • @yossico thanks good link helpful. But not a real question. Commented Jul 20, 2014 at 11:42

1 Answer 1

2

List.Add or List.Insert doesn't take variable length parameters. You may need to use List.AddRange method.

List<string> deck = new List<string>();
deck.AddRange(new []{"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"});
List<string> colour = new List<string>();
colour.AddRange(new []{"Hearts", "Diamonds", "Spades", "Clubs"});

Also note that I've converted the numerical parameters to string as the list is List<string>, otherwise it won't compile.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.