【问题标题】:C# create list with multiple entriesC# 创建包含多个条目的列表
【发布时间】:2014-09-11 01:42:30
【问题描述】:

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

学习 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);
    }
    }
}

我已尝试过添加和插入方法,但无法创建我的列表。

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

【问题讨论】:

标签: c#


【解决方案1】:

List.Add 或 List.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&lt;string&gt;,否则无法编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多