向列表中添加多个项目

29
static class Program
{
    static void Main(string carMake, string carModel, string carColour, string bikeModel, string bikeMake, string bikeColour, string truckMake, string truckModel, string truckColour)
    {
        car Mynewcar = new car();
        motorbike Mynewbike = new motorbike();
        truck Mynewtruck = new truck();

        int choice = 0;
        while (choice != 5)
        {

            Console.WriteLine("MENU");
            Console.WriteLine("What service do you need");
            Console.WriteLine("1. Car");
            Console.WriteLine("2. Motorbike");
            Console.WriteLine("3. Truck");
            Console.WriteLine("4. Search");
            Console.WriteLine("5. Exit");

            choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
                case 1:
                    Console.WriteLine("What is the car make?");
                    Mynewcar.make = Console.ReadLine().ToLower();
                    carMake = Console.ReadLine();
                    Console.WriteLine("");

                    Console.WriteLine("What is the car model?");
                    Mynewcar.model = Console.ReadLine().ToLower();
                    carModel = Console.ReadLine();
                    Console.WriteLine("");

                    Console.WriteLine("What is the car Colour?");
                    Mynewcar.colour = Console.ReadLine().ToLower();
                    carColour = Console.ReadLine();
                    Console.WriteLine("");

                    break;
                case 2:
                    Console.WriteLine("what is the motorbike make");
                    Mynewbike.make = Console.ReadLine().ToLower();
                    bikeMake = Console.ReadLine();
                    Console.WriteLine("");

                    Console.WriteLine("what is the motorbike model");
                    Mynewbike.model = Console.ReadLine().ToLower();
                    bikeModel = Console.ReadLine();
                    Console.WriteLine("");

                    Console.WriteLine("what is the motorbike colour");
                    Mynewbike.colour = Console.ReadLine().ToLower();
                    bikeColour = Console.ReadLine();
                    Console.WriteLine("");

                    break;
                case 3:
                    Console.WriteLine("what is the trucks make");
                    Mynewtruck.make = Console.ReadLine().ToLower();
                    truckMake = Console.ReadLine();
                    Console.WriteLine("");

                    Console.WriteLine("what is the trucks model");
                    Mynewtruck.model = Console.ReadLine().ToLower();
                    truckModel = Console.ReadLine();
                    Console.WriteLine("");

                    Console.WriteLine("what is the trucks colour");
                    Mynewtruck.colour = Console.ReadLine().ToLower();
                    truckColour = Console.ReadLine();
                    Console.WriteLine("");

                    break;
                case 4:
                    string searchchoice = "";
                    Console.WriteLine("select Car, Motobike or truck to search?");
                    searchchoice = Console.ReadLine().ToLower();
                    if (searchchoice.Equals("car"))
                    {
                        Console.WriteLine("Car in inventory: {0} - {1} - {2}", carMake, carModel, carColour);
                    }
                    else if (searchchoice.Equals("motorbike"))
                    {
                        Console.WriteLine("Motorbike in inventory: {0} - {1} - {2}", bikeMake, bikeModel, bikeColour);
                    }
                    else
                    {
                        Console.WriteLine("Trucks in inventory: {0} - {1} - {2}", truckMake, truckModel, truckColour);
                    }
                    Console.ReadLine();
                    break;
                case 5:
                    break;
                default:
                    Console.WriteLine("Sorry, invalid selection");
                    break;
            }
        }
    }

    class car
    {
        public string make { get; set; }
        public string model { get; set; }
        public string colour { get; set; }

        public List<String> carList(car Mynewcar)
        {
            List<String> caradd = new List<String>();
            caradd.Add(Mynewcar.make);
            string carMake = Mynewcar.make;

            caradd.Add(Mynewcar.model);
            string carModel = Mynewcar.model;

            caradd.Add(Mynewcar.colour);
            string carColour = Mynewcar.model;


            return caradd;
        }

    }
    class motorbike : car
    {
        public List<String> bikeList(motorbike Mynewbike)
        {
            List<String> bikeadd = new List<String>();
            bikeadd.Add(Mynewbike.model);
            string bikeModel = Mynewbike.model;

            bikeadd.Add(Mynewbike.make);
            string bikeMake = Mynewbike.make;

            bikeadd.Add(Mynewbike.colour);
            string bikeColour = Mynewbike.colour;

            return bikeadd;
        }
    }
    class truck : car
    {
        public List<String> truckList(truck Mynewtruck)
        {
            List<String> truckadd = new List<String>();
            truckadd.Add(Mynewtruck.make);
            string truckMake = Mynewtruck.make;

            truckadd.Add(Mynewtruck.model);
            string truckModel = Mynewtruck.model;

            truckadd.Add(Mynewtruck.colour);
            string truckColour = Mynewtruck.colour;

            return truckadd;
        }
    }
}

我在想,是否有人能够查看我的代码,并指出哪些方面还需要改进。

此外,我正在努力将多个项目添加到汽车、自行车和卡车的列表中。你会如何做,以便可以添加属性的多个实例并将它们列出到控制台?


1
作为以后的参考,对于这样的问题,您不需要几乎这么多的代码。其中大部分与问题完全无关。代码确实有帮助,但简洁的代码才是王道。 - AustinWBryan
5个回答

52

多亏了AddRange

例子:

public class Person
{ 
    private string Name;
    private string FirstName;

    public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}

要将多个Person添加到一个List<>中:

List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
    new Person("John1", "Doe" ),
    new Person("John2", "Doe" ),
    new Person("John3", "Doe" ),
 });

26

代码检查:

这个话题不在这里讨论,但是在CodeReview上的人们非常愿意帮助你。

我强烈建议你这样做,因为你的代码有几个需要注意的地方。同样,我建议你开始阅读教程,因为没有很好的理由不这样做。

列表:

正如你自己所说:你需要一个条目列表。现在的方法只存储一个项目的引用。幸运的是,恰好有一个可以容纳相关对象组的东西:List

列表的使用非常简单,但仍要查看相关文档。

以下是一个非常简单的示例,以将多个自行车保存在列表中:

List<Motorbike> bikes = new List<Motorbike>();

bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });

而要遍历列表,您可以使用foreach语句:

foreach(var bike in bikes) {
     Console.WriteLine(bike.make);
}

1
你可以像这样添加:var bikes = new List<Bike>(); bikes.AddRange(new List<Bike>{{new Bike { make = "Honda", color = "brown" }}, {new Bike { make = "Vroom", color = "red" }}}); - Shiljo Paulson
如果我有一个嵌套在另一个类中的列表,就像这样:https://pastebin.com/aWhfu8UM。我会收到一个“运行时异常(第9行):对象引用未设置为对象实例。”错误。我的实例化看起来与您发布的类似,但我的代码出现了错误。 - Si8

12

另一种有用的方法是使用Concat
在官方文档中获取更多信息。

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

输出结果将会是这样。

One
Two
Three
Four
Five

还有一个类似的答案


1
请记得导入 System.Linq,否则 concat 方法将无法使用。 - gebirgsbärbel

8

在现代的C#中,使用扩展方法(extension methods),泛型(generics)和params关键字,可以创建一个通用的方法(method),将不定数量的任意类型(type)项添加到List类(class)的列表(list)中:

static class ListExtensions 
{
  static public void Add<T>(this List<T> list, params T[] additions)
  {
    foreach(T addition in additions)
    {
      list.Add(addition)
    }
  }
}

使用字符串列表和整数列表的示例用法:

var stringList = new List<string>();
stringList.Add("Hello", "World", "!");

var intList = new List<int>();
intList.Add(1, 2, 3, 4, 5);

-2

AddRange是一个好的方法,如果你正在使用一个字符串列表,通过以下方式将"aa","bb","cc","dd"添加到该列表是非常简单的: list.AddRange("aa,bb,cc,dd".Split(',').ToList())


2
这个问题已经在4年前被另一个答案覆盖了。请尝试提供新信息的答案,以避免重复帖子造成噪音。 - Timothy G.
我认为这更容易。 - Anuradha Jayasena

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接