Search code examples
c#visual-studioclass-library

Creating a Table from a list of objects c#


I have Class of people that look like this:

    class Person
{
    public string firstName { get; }
    public string lastName { get; }
    public int age { get; set; }

    public Person(string firstName,string lastName, int age)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
}

I would like to be able to create a table from a list of persons that I can send via email that looks like this:

enter image description here

how can I do it ?

thanks


Solution

  • Try following :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<Person> people = new List<Person>();
    
                DataTable dt = new DataTable();
                dt.Columns.Add("firstname", typeof(string));
                dt.Columns.Add("lastname", typeof(string));
                dt.Columns.Add("age", typeof(int));
    
                foreach (Person person in people)
                {
                    dt.Rows.Add(new object[] { person.firstName, person.lastName, person.age });
                }
    
            }
        }
        class Person
        {
            public string firstName { get; set; }
            public string lastName { get; set;  }
            public int age { get; set; }
    
            public Person(string firstName, string lastName, int age)
            {
                this.firstName = firstName;
                this.lastName = lastName;
                this.age = age;
            }
        }
    }