c#创建包含多个条目的列表

时间:2014-07-20 11:33:36

标签: c#

如何创建包含固定条目集的列表。

学习C#并进行练习以列出一副牌中的所有牌(没有笑话)。要使用两个foreach循环打印出来。

但是我无法获得卡的默认列表(我正在重载方法)。查看文档http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx和一些示例http://www.dotnetperls.com/list,每个元素都会单独添加。

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

我尝试了Add和Insert方法,但无法创建我的列表。

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

1 个答案:

答案 0 :(得分:2)

List.AddList.Insert不接受可变长度参数。您可能需要使用List.AddRange方法。

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

另请注意,我已将数字参数转换为字符串,因为列表为List<string>,否则将无法编译。

相关问题