【问题标题】:Creating a Table from a list of objects c# [closed]从对象列表创建表c#[关闭]
【发布时间】:2021-01-25 23:33:23
【问题描述】:

我有这样一类人:

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

我希望能够从我可以通过电子邮件发送的人员列表中创建一个表格,如下所示:

我该怎么做?

谢谢

【问题讨论】:

  • 这不是数据表,您的类的构造函数名称不同。请edit你的问题提供一个正确的例子。
  • 这样做了,你能看看吗?
  • 可能 OP 指的是 HTML 表,但同样,我们需要更清楚地说明问题。
  • @Steve 我同意。 “通过电子邮件发送”是一个死的赠品。
  • 这太宽泛了。您至少需要尝试自己实现这一点。

标签: c# visual-studio class-library


【解决方案1】:

尝试以下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2022-01-05
    • 2017-06-26
    • 2018-11-24
    • 2011-09-07
    • 1970-01-01
    • 2021-07-22
    • 2012-09-27
    相关资源
    最近更新 更多