Add multiple items to a list

后端 未结 3 1350
孤独总比滥情好
孤独总比滥情好 2020-11-28 12:08
static class Program
{
    static void Main(string carMake, string carModel, string carColour, string bikeModel, string bikeMake, string bikeColour, string truckMake         


        
相关标签:
3条回答
  • 2020-11-28 12:33

    Another useful way is with Concat.
    More information in the official documentation.

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

    The output will be.

    One
    Two
    Three
    Four
    Five
    

    And there is another similar answer.

    0 讨论(0)
  • 2020-11-28 12:40

    Thanks to AddRange:

    Example:

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

    To add multiple Person to a List<>:

    List<Person> listofPersons = new List<Person>();
    listofPersons.AddRange(new List<Person>
    {
        new Person("John1", "Doe" ),
        new Person("John2", "Doe" ),
        new Person("John3", "Doe" ),
     });
    
    0 讨论(0)
  • 2020-11-28 12:50

    Code check:

    This is offtopic here but the people over at CodeReview are more than happy to help you.

    I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.

    Lists:

    As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List.

    Lists are very straightforward to use but take a look at the related documentation anyway.

    A very simple example to keep multiple bikes in a list:

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

    And to iterate over the list you can use the foreach statement:

    foreach(var bike in bikes) {
         Console.WriteLine(bike.make);
    }
    
    0 讨论(0)
提交回复
热议问题