Home > front end >  C#: Creating a Class List "List<Class>" and inserting a list of datas
C#: Creating a Class List "List<Class>" and inserting a list of datas

Time:01-19

Lets say you have a class List and you want to add other information from other list. How do you create 2 instance of objects or more and insert data from another List collection? See sample code below:

  using System;
  using System.Collections.Generic;
    
class Person
{
    public string Fname {get; set;}
    public string Lname {get; set;}
    public int age {get; set;}
}

class MainTest {
  static void Main() {
    
    //Console.WriteLine();
    List<string> FNames = new List<string> { "Ben", "John" };
    List<string> LNames = new List<string> { "Park", "Wilson" };
    List<int> Ages = new List<int> { 20,25};

    List<Person> PersonsL = new List<Person>();

    //Person = new Person();
    
    for (int i=0;i<2;i  )
    {
        Person = new Person();
        foreach (Person datas in PersonsL)
            {
                datas.Fname = FNames[i];
                datas.Lname = LNames[i];
                datas.age = Ages[i];
            }
    }
 
  }
}

CodePudding user response:

you don't need to iterate over PersonL, as this list literally has no elements. Just call PersonL.Add:

using System;
using System.Collections.Generic;

class Person
{
    public string Fname {get; set;}
    public string Lname {get; set;}
    public int age {get; set;}
}

class MainTest 
{
    static void Main() {
    
        //Console.WriteLine();
        List<string> FNames = new List<string> { "Ben", "John" };
        List<string> LNames = new List<string> { "Park", "Wilson" };
        List<int> Ages = new List<int> { 20,25};

        List<Person> PersonsL = new List<Person>();

        for (int i=0;i<2;i  )
        {
            var p = new Person();
            p.Fname = FNames[i];
            p.Lname = LNames[i];
            p.age = Ages[i];
            PersonL.Add(p)
        }
    }
}

alternativly you may also use an object-initializer:

PersonL.Add(new Person { Fname = FNames[i], Lname = LNames[i], age = Ages[i] });

CodePudding user response:

you can use Zip linq

List<Person> PersonsL = FNames.Zip(LNames, Ages)
.Select(fn => new Person {Fname=fn.First,Lname=fn.Second,age=fn.Third} ).ToList();

if you need, you can add it to another List

anotherList.AddRange(PersonL);
  •  Tags:  
  • Related